简体   繁体   English

带PowerMock和Mockito的受保护构造函数的测试类

[英]Testing class with Protected Constructor w/ PowerMock and Mockito

I have the following class to test: 我有以下课程要测试:

public abstract class Challenge {
    protected int id;
    protected String name;
    protected String question;

    protected Challenge(){}

    public String[] toStrings(){
        String[] s = {Integer.toString(id), name, question};
        return s; 
    }

    ...

But using this test: 但是使用此测试:

@Test
public void testToStrings() throws Exception{

    String[] expectedResult1 = new String[]{"1", "a", "b"};

    String[] obtainedResult1 = null;

    Challenge challengeMock = PowerMockito.mock(Challenge.class);
    challengeMock.id = 1;
    challengeMock.name = "a";
    challengeMock.question = "b";

    obtainedResult1 = challengeMock.toStrings();
    Assert.assertEquals(expectedResult1[0], obtainedResult1[0]);
    Assert.assertEquals(expectedResult1[1], obtainedResult1[1]);
    Assert.assertEquals(expectedResult1[2], obtainedResult1[2]);
}

I get a NullPointerException due to "obtainedResult1 = challengeMock.toStrings();" 由于“ obtainedResult1 = ChallengeMock.toStrings();”,我得到一个NullPointerException。 that returns null. 返回null。

I use PowerMock + Mockito running in Robolectric with rule(becouse its an Android project). 我使用带有规则的Robolectric运行PowerMock + Mockito(因为它是一个Android项目)。

@Rule
public PowerMockRule rule = new PowerMockRule();

Where is the problem? 问题出在哪儿?

You don't need PowerMock for this; 您不需要PowerMock; a Mockito mock will be just fine. 一个Mockito模拟就好了。 But normally, a mock has no functionality in its methods, which is why toStrings() isn't returning the value that you expect. 但是通常,模拟程序的方法没有功能,这就是为什么toStrings()不返回您期望的值的原因。 To change this, you need the CALLS_REAL_METHODS default answer. 要更改此设置,您需要CALLS_REAL_METHODS默认答案。

So my recommendation would be to change the line where you create the mock (the third non-empty line of testToStrings ) to something like this. 因此,我的建议是将创建模拟的行( testToStrings的第三条非空行)更改为类似的内容。

Challenge challengeMock = Mockito.mock(Challenge.class, Mockito.CALLS_REAL_METHODS );

I have tested this, and your test passes if you make this change. 我已经测试过了,如果进行了此更改,您的测试就会通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM