4

I am using Junit 4.8.2. When I run my test class with @RunWith(MockitoJUnitRunner.class) and just annotate mocks with @Mock, it doesn't seem to initialize the mocks. But when I use the static mock() and get rid of the runner and annotations, I can see that the mocks are initialized.

@RunWith(MockitoJUnitRunner.class)
public class MyTestClass
{
    private static final String DOMAIN = "mock";

    @Mock private TransactionManager transactionManager;
    @Mock private SearchManager searchManager;

    private final filter = new Filter(transactionManager,searchManager, DOMAIN);

    @Test
    public void myTest()
    {
        filter.callMethod();      // This throws NPE since transactionManager was null
    }
}

What am I doing wrong here? I have looked into this Initialising mock objects - MockIto and have done everything according to it but still no luck.

Community
  • 1
  • 1
Vivin
  • 1,327
  • 2
  • 9
  • 28
  • 8
    This post should have the answer to your question: http://stackoverflow.com/questions/15494926/initialising-mock-objects-mockito – Steve Jul 08 '16 at 18:45
  • @RC. You were right. If you want you can add it as an answer – Vivin Jul 08 '16 at 19:38

3 Answers3

5

The runner handles the @Mock annotation after the class is instantiated, so move the filter = new Filter(transactionManager,searchManager, DOMAIN); in a @Before annotated method:

@RunWith(MockitoJUnitRunner.class)
public class MyTestClass
{
    private static final String DOMAIN = "mock";

    @Mock 
    private TransactionManager transactionManager;

    @Mock 
    private SearchManager searchManager;

    private Filter filter;

    @Before
    public void setup() throws Exception {
        filter = new Filter(transactionManager, searchManager, DOMAIN);
    }

    @Test
    public void myTest() throws Exception {
        filter.callMethod(); // No more NPE
    }
}

From the runner doc:

Initializes mocks annotated with @Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.

1

Try initializing your mocks, adding a setup method to your test class.

You will also probably need to move your filter initialization inside it:

private filter;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
    filter = new Filter(transactionManager,searchManager, DOMAIN);
}
0

You can use @InjectMock over your test object. If you use @InjectMock , it will use mocked object to create your test object.

sauumum
  • 1,638
  • 1
  • 19
  • 36