Ashish Kumar
Ashish Kumar

Reputation: 926

Difference between @TestSubject and @InjectMocks?

While learning Mockito I found two different annotations @TestSubject and @InjectMocks at below references.
@TestSubject Ref
@InjectMocks Ref

@InjectMocks annotation is working absolutely fine as explained in tutorial but @TestSubject doesn't work rather its displaying error.
I'm getting TestSubject cannot be resolved to a type error for @TestSubject annotation in the below code snippet however I have done proper setup (including Junit & Mockito jar files in the build path).

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);
    }
}

I have two questions here.
1. Has some one encountered similar issue? If yes then what was the root cause and solution?
2. If it's working fine then what is the difference between @TestSubject and @InjectMocks annotations?

Upvotes: 5

Views: 3888

Answers (1)

Stefan Birkner
Stefan Birkner

Reputation: 24550

@TestSubject is the annotation of EasyMock that does the same like Mockito's @InjectMocks. If you're using Mockito then you have to use @InjectMocks.

Upvotes: 7

Related Questions