I am trying to mock ContextLoader.getCurrentWebApplicationContext() call in when using mockito but its fails to mock.
//here is my source code
@Mock
org.springframework.web.context.WebApplicationContext webApplicationContext;
//test Case Body
try (MockedStatic<ContextLoader> dummy = Mockito.mockStatic(ContextLoader.class)) {
AnswerInfo answerInfo = Mockito.mock(AnswerInfo.class);
TranDescScoreInfo descScoreInfo2 = Mockito.mock(TranDescScoreInfo.class);
when(ctx.getBean("answerInfo")).thenReturn(answerInfo);
when(ctx.getBean("tranDescScoreInfo")).thenReturn(descScoreInfo2);
dummy.when(() -> ContextLoader.getCurrentWebApplicationContext()).thenReturn(webApplicationContext);
//ContextLoader.getCurrentWebApplicationContext() getting null I dont why it getting null.
}
//Below Code is my business logic
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
AnswerInfo answerInfo = (AnswerInfo) ctx.getBean("answerInfo");
tranDescScoreInfo = (TranDescScoreInfo) ctx.getBean("tranDescScoreInfo");
// ctx.getBean getting null because i am not getting mock call here as expected Note: I don't want to change my business logic
You have to move the code inside the try. I hope this works for you: