异常
java.lang.NullPointerException
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:67)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:42)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:105)
at us.ny.state.ij.safeact.ask.facade.AmmoSellerKeeperFacadeBeanTest.setUp(FacadeBeanTest.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
代码模拟
BusinessServiceFactory serviceFactory = BusinessServiceFactory.getInstance();
RegBusinessServiceImpl regCreateService =
serviceFactory.getRegBusinessService(adrEntityManager);
测试代码
@RunWith(PowerMockRunner.class)
@PrepareForTest({ BusinessServiceFactory.class})
public class FacadeBeanTest {
@Before
public void setUp() throws Exception {
AmmoSellerRegBusinessServiceImpl mockRegBusinessServiceImpl
= mock(AmmoSellerRegBusinessServiceImpl.class);
PowerMockito.doReturn(mockRegBusinessServiceImpl)
.when(BusinessServiceFactory.class,"getRegBusinessService",
(mockEntityManager)); //--- line 84 null pointer exception
}
}
我无法理解为什么我会看到异常。我很感激任何建议。
答案 0 :(得分:1)
您必须使用Mockito.when()
来模拟返回值的方法。此外,您需要在模拟静态类的方法之前使用PowerMockito.mockStatic()
。
PowerMockito.mockStatic(BusinessServiceFactory.class);
// use Mockito to set up your expectation
Mockito.when(BusinessServiceFactory.getInstance())
.thenReturn(mockRegBusinessServiceImpl);
Mockito.when(mockRegBusinessServiceImpl.getRegBusinessService())
.thenReturn(mockEntityManager);
在这里查看PowerMock usage以便更好地理解。
答案 1 :(得分:1)
解决方案是使用 PowerMockito.mock()而不是 Mockito.mock()
你应该做
AmmoSellerRegBusinessServiceImpl mockRegBusinessServiceImpl
= PowerMockito.mock(AmmoSellerRegBusinessServiceImpl.class);
而不是
AmmoSellerRegBusinessServiceImpl mockRegBusinessServiceImpl
= mock(AmmoSellerRegBusinessServiceImpl.class);
// assuming your are using Mockito.mock()
// correct me if I am wrong
我也遇到了同样的问题。这个解决方案对我来说很合适。希望它有所帮助。