【问题标题】:Difference between @TestSubject and @InjectMocks?@TestSubject 和 @InjectMocks 之间的区别?
【发布时间】:2017-02-02 10:00:28
【问题描述】:

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

@InjectMocks 注释工作得很好,如教程中所述,但 @TestSubject 不起作用,而是显示错误。
我在下面的代码 sn-p 中收到 @TestSubject 注释的 TestSubject cannot be resolved to a type 错误,但是我已经完成了正确的设置(包括构建中的 JunitMockito 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 注释有什么区别?

【问题讨论】:

  • 我真的找不到任何证据证明这个注释确实作为 Mockito 的一部分存在。您链接到的教程甚至没有为其定义导入语句。对我来说似乎是一个错字,例如应该是@Spy

标签: java junit java-8 mockito


【解决方案1】:

@TestSubject 是 EasyMock 的注解,其作用与 Mockito 的 @InjectMocks 相同。如果您使用的是 Mockito,则必须使用 @InjectMocks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    • 2015-10-04
    • 2012-08-12
    • 2011-02-18
    • 2019-12-21
    相关资源
    最近更新 更多