【问题标题】:Run unit test independently without involving spring独立运行单元测试,不涉及 spring
【发布时间】:2015-11-04 12:35:40
【问题描述】:

我的申请写在spring boot。 我正在使用testNGmockito 进行单元测试。

我对单元测试的工作有点困惑。

以下是我的测试课

class StudentServiceTest {
    @mock
    StudentDAO studentDAO;

    @InjectMocks
    StudentService studentService;

    @BeforeMethod
    public void initMock() {
        studentService = new StudentService();
        MockitoAnnotations.initMocks(this);
    }

    @Test(dataprovider.....)
    public void shouldxxxxx(int id......) {
       when(studentDAO.findOne(id)).thenReturn(Student);
       assert......
    }
}

当我运行上面的测试时。它工作正常。

我有以下疑问。

  1. 是否涉及弹簧。如果不是,那么@mock 和其他代码是如何工作的
  2. 我们是否应该涉及 spring。如果不/是,为什么?
  3. 我使用了new关键字来初始化服务。好吗。 正如在spring unit test documentation 中他们所说的那样

您可以使用 new 运算符简单地实例化对象,甚至无需涉及 Spring。您还可以使用模拟对象而不是真正的依赖项

如果我不使用 new 关键字实例化服务,则会显示错误 “无法实例化 @InjectMocks”。

如果我 autowired 服务,那么它需要 spring 容器,而且我运行单个测试,运行时间太长。如果not autowired 并使用new 关键字,那么它运行得非常快。

  1. 上面的代码干净吗?请建议使用 testNg 和 mockito 在 Spring Boot 中编写单元测试的最佳实践。

【问题讨论】:

    标签: spring unit-testing spring-boot testng mockito


    【解决方案1】:
    1. 是否涉及弹簧。如果不是,那么@mock 和其他代码如何工作

      我猜不,因为你在嘲笑每一件事。

    2. 我们应该使用弹簧吗?

      不,除非你想使用 spring 管理的 bean。

    3. 我使用了新的关键字来初始化服务。

      甚至不需要使用 new 关键字来实例化服务。确保您的initMock() 方法使用org.junit.Before 注释进行注释,并使用MockitoAnnotations.initMocks(this); 进行初始化模拟

      如果您注意这一点,您应该不会看到 无法实例化 @InjectMocks 错误

    4. 上面的代码干净吗?

      当然,如果您注意 3 个要点,它将是干净的代码。

    你的测试课应该是休闲的。

    class StudentServiceTest {
       @mock
       StudentDAO studentDAO;
    
       @InjectMocks
       StudentService studentService;
    
       @org.junit.Before
       public void initMock() { 
          MockitoAnnotations.initMocks(this);
       }
    
       @Test(dataprovider.....)
       public void shouldxxxxx(int id......) {
          when(studentDAO.findOne(id)).thenReturn(Student);
          assert......
       }
    }
    

    【讨论】:

    • 谢谢。一个疑问,如果我使用的是 testNg,那么为什么使用 junit 的 @Before?我试过了,但 studentDAO 和 studentService 为空,因此 NPE
    • 我对TestNG不太熟悉,你确定使用@BeforMethod注解时initMock()方法是在实际测试之前执行的吗?
    • 是的。它总是在每个方法之前执行,因此不需要显式清理。购买对我来说清楚的方式。但是你能解释一下这个@mock和其他代码是如何在没有spring容器的情况下工作的吗?
    • 基本上你是在模拟真实的对象,mockito 框架为标记为@Mock 的字段创建存根,@InitMock 将这些存根作为依赖注入。您无法打印模拟对象引用,因为它实际上并未实例化。这个链接可以帮助你理解 mock stackoverflow.com/questions/2665812/what-is-mocking
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 2013-05-27
    • 1970-01-01
    • 2021-03-02
    • 2012-03-03
    • 2019-05-02
    • 2017-02-20
    • 2021-07-13
    相关资源
    最近更新 更多