【发布时间】: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 错误,但是我已经完成了正确的设置(包括构建中的 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 注释有什么区别?
【问题讨论】:
-
我真的找不到任何证据证明这个注释确实作为 Mockito 的一部分存在。您链接到的教程甚至没有为其定义导入语句。对我来说似乎是一个错字,例如应该是
@Spy。