【发布时间】:2020-10-25 07:36:20
【问题描述】:
我正在使用 Mockito 来模拟服务层的方法。 这是我的测试代码。
@InjectMocks
MyServiceImpl myServiceImpl;
@Mock
MyDAO myDAO;
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void getAllFail(){
Mockito.when(myDAO.getAll().thenThrow(new DataException("mock"));
exceptionRule.expect(ServiceException.class);
myServiceImpl.getAllData();
}
服务代码
@Service
public class myServiceImpl extends myService{
private final MyDAO myDAO;
...
@Override
public List getAllData(){
try{
return myDAO.getAll();
} catch (DataException exception){
throw new ServiceException("exception");
}
}
}
一开始我以为通过mock DAO类抛出异常,会被catch捕获,变成ServiceException,结果却是
java.lang.AssertionError:
Expected an instance of com.example.exception.ServiceException
but: <com.example.exception.DataException: mock> is a com.example.exception.DataException
在这种情况下,我如何测试我的服务的异常情况?请指导我。提前谢谢你。
【问题讨论】:
-
您的代码无法编译。
Mockito.when(myDAO.getAll().thenThrow(new DataException("mock"));行缺少)。 -
Mockito 无法模拟决赛:
private final MyDAO myDAO; -
您使用的是 JUnit 4 还是 JUnit Jupiter?
标签: java spring junit mockito spring-test