2

例外

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
    }
}

我不明白为什么我会看到异常。我会很感激任何建议。

4

2 回答 2

4

供参考:

解决方案是使用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

我也面临同样的问题。这个解决方案是我的解决方案。希望能帮助到你。

于 2018-06-07T16:48:15.153 回答
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 用法以获得更好的理解。

于 2015-09-24T21:51:16.703 回答