3

@Mock object instance is null .

I am doing this is my test class

@Mock
private SchoolRequest schoolRequest;

@InjectMock
private FormRequest formRequest;

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

Class FormRequest {

@Autowired 
private SchoolRequest schoolRequest;


}

This application is running properly, but in test cases schoolRequest is coming as null. Any pointer on why it might happen ?

7
  • Can you provide a sample code which reproduces your problem? Commented May 2, 2017 at 10:00
  • it's very big code base. can't put whole code . Commented May 2, 2017 at 10:04
  • is SchoolRequest final? Commented May 2, 2017 at 11:17
  • @MaciejKowalski , No it's not, Commented May 2, 2017 at 12:07
  • Where are your test methods located? Are they in the same class as init()? Perhaps put a breakpoint on the initMocks() call and run one of your tests in debug to see if it's called. Commented May 2, 2017 at 14:19

3 Answers 3

7

I think you are missing @RunWith annotation on class level. Whenever you want to use the @Mock annotation you should use the MockitoJUnitRunner.

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private SchoolRequest schoolRequest;

@InjectMock
private FormRequest formRequest;

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

I hope this should work for you..

Sign up to request clarification or add additional context in comments.

1 Comment

6

I don't know the reason but this worked.

private SchoolRequest schoolRequest = Mockito.mock(SchoolRequest.class); 

May be someone can comment why this worked. What is difference between @Mock and Mockito.mock . I thought they are same.

1 Comment

In order to mock objects using annotation, you should use @org.junit.jupiter.api.Test for your test methods with junit5
1

Using ExtendWith has resolved my issue

@ExtendWith(MockitoExtension.class)
class PageTest {

  @Mock
  MyClass myclass;
}

Use below dependency for same

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>{LATEST_VERSION}</version>
</dependency>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.