@TestSubject和@InjectMocks之间的区别?

时间:2017-02-02 10:00:28

标签: java junit java-8 mockito

在学习 Mockito 时,我在以下参考文献中找到了两个不同的注释 @TestSubject @InjectMocks
@TestSubject Ref {
{3}}

正如教程中所解释的那样,@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注释之间有什么区别?

1 个答案:

答案 0 :(得分:6)

@TestSubject是EasyMock的注释,与Mockito的@InjectMocks一样。如果您正在使用Mockito,那么您必须使用$userCollectionName = '_profiles'; $collectionHandler = new CollectionHandler($arango); $userCollection = $collectionHandler->has($userCollectionName) ? $collectionHandler->get($userCollectionName) : $collectionHandler->create($userCollectionName);