【问题标题】:Mockito thenThrow cannot be catchMockito thenThrow 不能被抓住
【发布时间】: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


【解决方案1】:

我认为当您期望方法调用出现异常并且需要正确链接异常时,您需要使用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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2023-03-03
    • 2017-02-03
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多