【问题标题】:Mockito NullPointer Exception for the method called on Mock Object在 Mock 对象上调用的方法的 Mockito NullPointer 异常
【发布时间】:2020-10-02 21:31:06
【问题描述】:

当第一个 when(creditApplicationCache.getObject("")).thenRetun(response) 被调用时,我得到了一个 NPE。 creditApplicationCache 为空。

  1. 我正在使用 mockito 2.17.jar。
  2. 我添加了@RunWith(MockitoJUnitRunner.class)。
  3. 我也尝试过使用 MockitoAnnotations.initMocks(this)。

但没有任何帮助。 CreditApplicationCache 未初始化。

@RunWith(MockitoJUnitRunner.class)
public class WebServiceClientTest {
    
    @InjectMocks
    WebServiceClientImpl webServiceClientImpl;
    
    @Mock
    private ApplicationCacheImpl creditApplicationCache;
        
    /*@Before
    public void setUp()  {
        MockitoAnnotations.initMocks(this);
    }*/

    @Test
    public void testWebServiceClient() throws BusinessException, SystemException {
        WebServiceClientImpl webServiceClientImpl = new WebServiceClientImpl();         
        
        CreditCardDetailsResponse creditCardDetailsResponse = new CreditCardDetailsResponse();
        creditCardDetailsResponse.setAccountNumber("1234567");
        
when(creditApplicationCache.getObject("XXXXXXX")).thenReturn(creditCardDetailsResponse);         
 when(webServiceClientImpl.getCreditCardDetails("1234")).thenReturn(creditCardDetailsResponse);
        CreditCardDetailsResponse mockResponse = webServiceClientImpl.getCreditCardDetails("1234");
            
        assertEquals(creditCardDetailsResponse.toString(),mockResponse.toString());             
    }
}
---------------------------------------------------------------------------------------------------------
WebServiceClientImpl.java

public class WebServiceClientImpl implements WebServiceClient {
@Autowired
private ApplicationCache creditApplicationCache;

public CreditCardDetailsResponse getCreditCardDetails(String id)
            throws BusinessException, SystemException {
        // Some Code
    CreditCardDetailsResponse response = null;
        
        response = (CreditCardDetailsResponse) creditApplicationCache.getObject(cacheKey);
        if (response == null) {
            try {
             // More Code }
    return response ;

  }
}

【问题讨论】:

    标签: java spring junit mockito


    【解决方案1】:

    您的问题是您在测试的第一行再次创建客户端:WebServiceClientImpl webServiceClientImpl = new WebServiceClientImpl();

    @InjectMocks 已经构造了带注释的类,并注入了所有相关的模拟,但你要做的是在没有它的情况下重新创建它,因此是 NPE。

    只需删除该行,它应该可以工作

    【讨论】:

      【解决方案2】:

      当您从 org.junit.jupiter.api.Test 而不是 org.junit.Test 导入 @Test 时,可能会出现此问题。您能确保您使用的是正确的@Test 注释吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-02
        相关资源
        最近更新 更多