我试图在使用mockito时模拟contextloader.getcurrentwebapplicationcontext()调用,但它无法模拟。
//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");
//getbean获取null是因为我没有得到预期的模拟调用注意:我不想更改我的业务逻辑
2条答案
按热度按时间f3temu5u1#
你必须把代码移到try里面。我希望这对你有用:
cgyqldqp2#