user2340345
user2340345

Reputation: 853

How to get away with NPE for @Inject field while unit testing?

Im writing unit tests for the below code, Im getting NPE even though Im mocking the fields, How can I resolve that. Those fields are present with @Inject annotation

@Component
interface A {
    void run();
}

class B {
    @Inject
    A a;

    void someMethod() {
        a.run();
    }}

class C{
    @Inject
    B b;

    void anotherMethod() {
        b.someMethod();
    }
}

class CTest {
    @Mock
    B b;
    // remains null when invoked in the actual class though its mocked instance is
    // present here

    @Mock
    A a;
    //// remains null when invoked in the actual class though its mocked instance
    //// is present here

    @InjectMocks
    C c;

    @Before
    public void initialize() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {
        c.anotherMethod();
    }

}

So how can I get the mocked value in the actual class where the field is injected with @Inject using Mockito?

Upvotes: 2

Views: 430

Answers (1)

Vasily Vlasov
Vasily Vlasov

Reputation: 3346

My guess is that you should annotate your CTest class with @RunWith(MockitoJUnitRunner.class) and remove your before-method as it will become unecessary (@RunWith will do the trick of injecting mocks).

UPDATE

Actually I ran your code in my IDE. And everything is just fine, no NPE. Probably you have to check that your imports are correct. Here are mine to compare with yours:

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import javax.inject.Inject;
import org.springframework.stereotype.Component;

Also, please, pay attention that you declared Class C with upper case letter (should be class C) in your question, thus this very code won't compile.

Upvotes: 1

Related Questions