问题描述
我正在使用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");
}
}
}
起初我以为通过模拟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
在这种情况下,如何测试我的服务异常?请指导我。预先谢谢你。
解决方法
我认为,当您期望方法调用产生异常时,您需要使用Assertions.assertThrows
,并且需要正确地链接该异常。这是我的方法。
带有异常和方法调用的服务类
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
@Service
public class SampleTestService {
private final MyDao myDao;
public SampleTestService(MyDao myDao) {
this.myDao = myDao;
}
public List<String> getData() {
try {
return myDao.getStringList();
} catch (MyDao.DataException dataException) {
throw new ServiceException("Error getting data");
}
}
static class ServiceException extends RuntimeException {
public ServiceException(String message) {
super(message);
}
}
}
class MyDao {
public List<String> getStringList() {
return Collections.emptyList();
}
static class DataException extends RuntimeException {
public DataException(String message) {
super(message);
}
}
}
正在运行的单元测试类
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.Arrays;
import java.util.List;
@ExtendWith(SpringExtension.class)
class SampleTestServiceTest {
// private final MyDao myDao = mock(MyDao.class);
@Mock
MyDao myDao;
@Test
void testDaoThrowsException() {
Mockito.when(myDao.getStringList()).thenThrow(new MyDao.DataException("Error connecting to database"));
SampleTestService sampleTestService = new SampleTestService(myDao);
Assertions.assertThrows(SampleTestService.ServiceException.class,() -> {
sampleTestService.getData();
});
}
@Test
void testDaoReturnData() {
List<String> colors = Arrays.asList("red","green","blue");
Mockito.when(myDao.getStringList()).thenReturn(colors);
SampleTestService sampleTestService = new SampleTestService(myDao);
List<String> data = sampleTestService.getData();
Assertions.assertEquals(3,data.size());
Assertions.assertSame(data,colors);
}
}