java - Junit 测试 @InjectMocks 类中的异常

标签 java spring exception junit mockito

我的应用程序中有以下代码。

有人可以帮我为此编写一个测试用例吗?

Service.java

```public class Service{
public void createMessage(){
try{
LOG.info("message sent");
}catch(JAXBException){
LOG.info("exception occured");
}
}```

ServiceTest.java

```public class ServiceTest{
@InjectMocks
Service service;

@Test
public void testCreateMessageException(){
doThrow(JAXBException.class).when(service.createMessage));
}```

我尝试了上面的测试用例,但它给了我以下错误。 org.mockito.exceptions.misusing.MissingMethodInitationException: when() 需要一个参数,该参数必须是“模拟上的方法调用”。 例如: when(mock.getArticles()).thenReturn(articles);

最佳答案

您的理解是正确的,您不能在用@InjectMocks(正在测试的系统)注释的服务上使用when().then()。它必须用于被测系统中 Autowiring 的服务。

https://www.vogella.com/tutorials/Mockito/article.html

关于java - Junit 测试 @InjectMocks 类中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61399627/

相关文章:

java - ManyToMany with CascadeType.ALL 导致 Detached entity passed to persist

java - 使用扫描仪出现 NoSuchElementException

java - 线程 "main"java.lang.RuntimeException : Stub 中的异常

java - 当所有消息都被过滤后停止路由

java - 公开使用的 Vector 中的私有(private)类

javascript - KnockoutJS - 打印迭代索引作为输入名称

java - Spring MVC 3.2 - 错误页面的内容协商?

c++ - 级联 Poco 异常

java - BaseAdapter 类 getView() 中的 Layoutinflater 空指针异常

java - Java中的线程何时从内存中删除?