当前位置: 首页 > 知识库问答 >
问题:

Mockito then Throw无法接住

怀浩大
2023-03-14

我正在使用莫基托来模拟服务层的方法。这是我的测试代码。

@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类抛出exception,它会被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

在这种情况下,如何测试我的服务的异常?请引导我。提前感谢您。

共有1个答案

梁丘俊人
2023-03-14

我认为您需要使用断言。当您期望方法调用出现异常,并且需要正确链接异常时,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);
    }
}
 类似资料:
  • 连接到hadoop时,出现以下错误 线程“main”java.lang.AbstractMethodError中出现异常:org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider。getProxy()Lorg/apache/hadoop/io/retry/failoverproxy提供程序$ProxyInfo

  • Q-我安装了git以获取最新版本的Angular。当我尝试运行时 我连接到github 443错误失败 我甚至试过 这使我无法连接,没有错误消息。 我在公司防火墙后面。转到控制面板时,我看不到我的代理详细信息- 我终于做到了。我将更新我所采取的程序,以便只是想编译我所做的所有步骤,以使它正常工作

  • 我试图在独立模式下部署Hbase以下这篇文章:http://hbase.apache.org/book.html#quickstart.版本是0.92.1-cdh4.1.2 但我得到这些错误时,试图创建一个表: 错误消息: 输出日志: 我的配置: > 在hbase env中添加了JAVA_HOME。上海 hbase_网站。xml 我试图修改/etc/hosts,它看起来像这样(oracle是主机名

  • 问题内容: 我经常收到ServiceStack.Redis:无法连接:sPort:0或ServiceStack.Redis:无法连接:sPort:50071(或其他端口号)。 当我们的网站繁忙时,似乎会发生这种情况。Redis本身看起来很好,CPU或内存使用量并未真正增加。 我正在使用连接池,并尝试更改超时值,但未成功。 用法是这样的: 问题答案: 这是由于Redis在Hyper-V上作为虚拟机托

  • 我已经在互联网上搜索了一两个星期,想找到一个UDP客户端程序,它可以同时发送和接收数据,但是对于c#来说,没有关于这个主题的内容。在过去的几天里,我尝试创建一个UDP客户端,其中包含一个接收数据的线程。 发送UDP数据包效果很好,但程序无法接收我发送到的服务器,我相信服务器正在将所有数据包发送到不同的端口。 我如何修复这个程序? 有没有一种更简单的方法来进行UDP编程,比如用于TCP的Stream

  • 问题内容: 我正在尝试使用Ruby on Rails运行Selenium的示例脚本。我必须使用代理运行它。这是我的代码: 我收到以下错误: 有人能帮我吗…?我已经尝试了好几个小时,却找不到问题…真的不知道该怎么办。 环境: Ubuntu 16.04 LTS,Firefox 45.0,rbenv 2.3.1 另一个问题:有人知道Selenium + Ruby on Rails的示例吗?我找不到真正好