gpt4 book ai didi

java - 如何使用Mockito解决服务实例化中的NullPointer异常?

转载 作者:行者123 更新时间:2023-12-01 17:38:40 26 4
gpt4 key购买 nike

我有两个测试,第一个测试正常,第二个测试失败。看起来服务是空的,但是@InjectMocks不应该避免这种情况吗?我尝试过 @Spy、@Before 来设置模拟,但都没有成功......有人可以帮助我吗?

类(class)在上面

@RunWith(MockitoJUnitRunner.class)
public class ElegibilidadeMultiplaServiceTest {

@Spy
@InjectMocks
private ElegibilidadeMultiplaService elegibilidadeMultiplaService;

@Mock
private MessageFac message;

@Test
public void obterElegibilidadeComSucesso() throws Exception {

Mockito.doReturn(retornaVerdadeiro()).when(elegibilidadeMultiplaService)
.executeAndLogSoap(Mockito.any(), Mockito.any());

Map<Long, Boolean> mapa = elegibilidadeMultiplaService.consultaElegibilidadeListaEC(getListaEcs());

assertFalse(mapa.isEmpty());

}

@Test(expected = Exception.class)
public void deveLancarExcecaoGenerica() throws Exception {

Mockito.doThrow(Exception.class).when(elegibilidadeMultiplaService)
.executeAndLogSoap(Mockito.any(), Mockito.any());

elegibilidadeMultiplaService.consultaElegibilidadeListaEC(getListaEcs());

}

private List<Long> getListaEcs() {

List<Long> numerosEC = new ArrayList<>();

add objects to list

return numerosEC;
}

private VerificarClienteExistenteResponseType retornaVerdadeiro() {

VerificarClienteExistenteResponseType resp = new VerificarClienteExistenteResponseType();
resp.setIndicadorClienteExistente(Boolean.TRUE);

return resp;
}
}

最佳答案

实际上,考虑到我的方法实现,我做错了一些事情。这应该是测试

    @Test
public void deveFalharAoMontarMapa() throws Exception {

Mockito.doThrow(Exception.class)
.when(elegibilidadeMultiplaService)
.executeAndLogSoap(Mockito.any(), Mockito.any());

Map<Long, Boolean> mapa = elegibilidadeMultiplaService.consultaElegibilidadeListaEC(getListaEcs());

assertTrue(mapa.isEmpty());
}

多亏了 Stefan Helmerichs,我才知道出了什么问题。异常并不完全是我期望的方法返回,只是它的一部分。

关于java - 如何使用Mockito解决服务实例化中的NullPointer异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61001948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com