English 中文(简体)
Power Mokito do Nothing() on private setter Null Pointer
原标题:PowerMokito doNothing() on private setter NullPointer

问题:试图执行PowerMockito.doNothing()时提出的Nullpointer例外。

我需要建立一个部分MockObject的班级,将回报一种私人方法价值,对另一种私人制造方法则无所作为。

如果我用“压力”取代“Nothing()”的话,我就能够这样做,但我要指出这一点。

Code:

@Test
public void testPowerMockito() throws Exception
{       

    final String methodName1 = "Method1";
    final String methodName2 = "Method2";

    //Using PowerMockito
    ObjectToTest partialMockObject = PowerMockito.spy(new ObjectToTest());

    //Mock the private method, expect that a false
    PowerMockito.doReturn(false).when( partialMockObject,methodName1 );

    //Do Nothing on the void private setter     
    PowerMockito.doNothing().when( ObjectToTest.class,methodName2 );

    String result = partialMockObject.methodToTest();

    assertEquals("Fail","",result);

    //Confirms that the private method was called
    PowerMockito.verifyPrivate(partialMockObject).invoke(methodName1);
    PowerMockito.verifyPrivate(partialMockObject).invoke(methodName1);

}

StackTrace: java.lang.NullPointerException at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:68) at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:43) at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:104)

问题回答

我已广泛使用PowerMockito,试图并处理一些trick式 Java法的写作单位测试。 我可以告诉你,你所认为的工作并非一切都能够奏效,在线实例是不同的年龄和质量。 这种间谍活动是为了进行核查,但我很少利用PowerMockito进行模拟私人电话。

您确实有两种可能的行动: • 确保私人方法得到保护(然后,你只能使用Mockito部分模拟来做你想要做的事情),或重新制定法典,使你没有这些私人方法,并且能够打上其他物体,从而对公共电话有完全的模拟控制。 我不知道,当然,你在哪些其他制约因素下工作。





相关问题
Run JUnit automatically when building Eclipse project

I want to run my unit tests automatically when I save my Eclipse project. The project is built automatically whenever I save a file, so I think this should be possible in some way. How do I do it? Is ...

Embedded jetty ServletTester serving single static file

I m unit testing with jetty and I want to serve not only my servlet under test but a static page as well. The static page is needed by my application. I m initializing jetty like this tester = new ...

Applying one test to two separate classes

I have two different classes that share a common interface. Although the functionality is the same they work very differently internally. So naturally I want to test them both. The best example I ...

热门标签