如何模拟自定义util类?我收到以下错误:
[ERROR] 2019-08-20 12:06:02:197 [] com.metlife.api.clientlibrary.util.JWSRequestUtil.prepareRequestJWS():71 - Exception in preparing JWS request ::
java.lang.NullPointerException: null
代码是:
public class EPartnerPromotionHelperTest {
@InjectMocks
EPartnerPromotionHelper ePartnerPromotionHelper;
@Mock
private JWSRequestUtil jwsRequestUtil;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSavePromotion() throws Exception {
String loggerId = "loggerId";
PromotionDTO promotionDTO = new PromotionDTO();
promotionDTO.setDescription("description");
promotionDTO.setCreationDate(new Date());
promotionDTO.setModifiedDate(new Date());
Mockito.when(jwsRequestUtil.prepareRequestJWS(Matchers.any(EPartnerRestRequestDTO.class)
,Matchers.any(Boolean.class))).thenReturn("test");
PromotionDTO response =ePartnerPromotionHelper.savePromotion(loggerId,promotionDTO);
assertNotNull(response);
}
}
答案 0 :(得分:0)
假设错误消息来自prepareRequestJWS
方法的调用,则可以更改语法并改用doReturn
。
Mockito.doReturn("test")
.when(jwsRequestUtil)
.prepareRequestJWS(Matchers.any(EPartnerRestRequestDTO.class),
Matchers.any(Boolean.class));
这样编写,将不会调用prepareRequestJWS
方法,请检查Overriding a previous exception-stubbing
方法的javadoc中描述的doReturn
部分。这也适用于在调用它们时会抛出Exception的普通方法。
但是,一个问题是,为什么该异常首先来自您的JwsRequestUtil
类。随时将相关代码添加到您的问题中。