如何模拟从抽象类继承的受保护子类方法? [英] How to mock protected subclass method inherited from abstract class?

查看:903
本文介绍了如何模拟从抽象类继承的受保护子类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Mockito或PowerMock来模拟由子类实现但是从抽象超类继承的受保护方法?

How to use Mockito or PowerMock to mock a protected method that is realized by a subclass, but inherited from an abstract super class?

换句话说,我想要在模拟doSomethingElse时测试doSomething方法。

In other words, I want to test "doSomething" method while mocking the "doSomethingElse".

抽象超类

public abstract class TypeA {

    public void doSomething() {     

        // Calls for subclass behavior
        doSomethingElse();      
    }

    protected abstract String doSomethingElse();

}

子类实施

public class TypeB extends TypeA {

    @Override
    protected String doSomethingElse() {
        return "this method needs to be mocked";
    }

}

解决方案

Solution

此处给出的答案是正确的,如果涉及的课程属于同一个套餐,则会有效。

Answers given here are correct and will work if classes involved are in the same package.

但是如果涉及不同的包,则一个选项是用户PowerMock。以下示例适用于我。当然可能有其他方法可以做到这一点。这是有效的。

But if different packages are involved one option is to user PowerMock. The following example worked for me. Of course there might be other ways of doing it, this is one that works.

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ TypeB.class })
public class TestAbstract {

    @Test
    public void test_UsingPowerMock() throws Exception {
        // Spy a subclass using PowerMock
        TypeB b = PowerMockito.spy(new TypeB());
        String expected = "some value for mock";

        // Mock a method by its name using PowerMock again
        PowerMockito.doReturn(expected).when(b, "doSomethingElse");

        // Calls the 
        String actual = b.doSomething();
        assertEquals(expected, actual);     

    }
}

注意:测试完成使用Java 5,jUnit 4.11,Mockito 1.9.0和PowerMock 1.4.12。

推荐答案

你可以用<模拟抽象方法时code> Mockito.CALLS_REAL_METHODS 。这将调用类的原始方法,您可以自己模拟所有抽象方法。

You can use Mockito.CALLS_REAL_METHODS when mocking the abstract method. This will call the originals methods of the class and you can mock all abstract methods by yourself.

TypeA typeA = mock(TypeA.class, Mockito.CALLS_REAL_METHODS);
when(typeA.doSomethingElse()).thenReturn("Hello");
typeA.doSomething();

或者您使用间谍直接在TypeB上进行测试:

Or you test directly on the TypeB with a spy:

TypeB typeB = spy(new TypeB());
when(typeB.doSomethingElse()).thenReturn("Hello");
typeB.doSomething();

这篇关于如何模拟从抽象类继承的受保护子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆