java - @TestSubject 和@InjectMocks 之间的区别?

标签 java junit java-8 mockito

在学习 Mockito 时,我在下面的引用资料中发现了两个不同的注释 @TestSubject@InjectMocks
@TestSubject Ref
@InjectMocks Ref

@InjectMocks 注释工作得很好,如教程中所述,但 @TestSubject 不起作用,而是显示错误。
我在下面的代码片段中收到 TestSubject cannot be resolved to a type 错误,因为 @TestSubject 注释但是我已经完成了正确的设置(包括 Junit & Mockito 构建路径中的 jar 文件)。

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import com.infosys.junitinteg.action.MathApplication;
import com.infosys.junitinteg.service.CalculatorService;

@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {

    // @TestSubject annotation is used to identify class which is going to use
    // the mock object
    @TestSubject
    MathApplication mathApplication = new MathApplication();

    // @Mock annotation is used to create the mock object to be injected
    @Mock
    CalculatorService calcService;

    @Test(expected = RuntimeException.class)
    public void testAdd() {
        // add the behavior to throw exception
        Mockito.doThrow(new RuntimeException("Add operation not implemented")).when(calcService).add(10.0, 20.0);

        // test the add functionality
        Assert.assertEquals(mathApplication.add(10.0, 20.0), 30.0, 0);
    }
}

我有两个问题。
<强>1。有人遇到过类似的问题吗?如果是,那么根本原因和解决方案是什么?
2. 如果它工作正常,那么 @TestSubject@InjectMocks 注释有什么区别?

最佳答案

@TestSubject是 EasyMock 的注释,与 Mockito 的 @InjectMocks 相同.如果您使用的是 Mockito,则必须使用 @InjectMocks

关于java - @TestSubject 和@InjectMocks 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999135/

相关文章:

java - 在 Spring Boot 中的 JUnit 测试中创建 bean 时出错

android - 使用 Kotlin 在 Android 中的测试中声明 @BeforeClass 的正确方法是什么

JAVAFX:有什么办法可以获得已经开放的舞台吗?

java - 序列化 CompletableFuture 字节码

c# - 二叉搜索树中的重复条目

java - 无法将图像加载到缓冲图像二维数组中

Java dateFishion 编码

java - 是否可以在不使用instanceof和getClass的情况下覆盖equals?

java - 如何模拟 Autowired 对象(java)并将其注入(inject)到 Spock 中的 spy 对象中

java-8 - 收集字符串列表以使用 Java 8 Stream API 进行映射