Mock ContextLoader.getCurrentWebApplicationContext() call using when in mockito .How can i do that?

huangapple go评论75阅读模式
英文:

Mock ContextLoader.getCurrentWebApplicationContext() call using when in mockito .How can i do that?

问题

我正在尝试在使用Mockito时模拟ContextLoader.getCurrentWebApplicationContext()调用,但是无法成功模拟。

以下是我的源代码示例:

@Mock
org.springframework.web.context.WebApplicationContext webApplicationContext;

// 测试用例主体
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()返回null,我不知道为什么会返回null。
}

// 下面的代码是我的业务逻辑
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
AnswerInfo answerInfo = (AnswerInfo) ctx.getBean("answerInfo");
tranDescScoreInfo = (TranDescScoreInfo) ctx.getBean("tranDescScoreInfo");

// ctx.getBean返回null,因为我没有按预期获得模拟调用
注意我不想更改我的业务逻辑

请注意,我只翻译了你提供的源代码部分,不包含额外的内容。如果你有任何其他需要翻译的内容,请继续提供。

英文:

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&lt;ContextLoader&gt; dummy = Mockito.mockStatic(ContextLoader.class)) {
                    
AnswerInfo answerInfo = Mockito.mock(AnswerInfo.class);
                    
TranDescScoreInfo descScoreInfo2 = Mockito.mock(TranDescScoreInfo.class);
                    
when(ctx.getBean(&quot;answerInfo&quot;)).thenReturn(answerInfo);
when(ctx.getBean(&quot;tranDescScoreInfo&quot;)).thenReturn(descScoreInfo2);
                    
dummy.when(() -&gt; 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(&quot;answerInfo&quot;);
 tranDescScoreInfo = (TranDescScoreInfo) ctx.getBean(&quot;tranDescScoreInfo&quot;);

// ctx.getBean getting null because i am not getting mock call here as expected
Note: I don't want to change my business logic

答案1

得分: 1

你必须将代码移到try块内。我希望这对你有用:

class UserTest {
    @Mock
    WebApplicationContext webApplicationContext;

    @BeforeEach
    void setUp() throws Exception {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void test() {

        // 测试用例主体
        try (MockedStatic<ContextLoader> dummy = Mockito.mockStatic(ContextLoader.class)) {
            Mockito.when(webApplicationContext.getBean("answerInfo")).thenReturn(new String());
            dummy.when(ContextLoader::getCurrentWebApplicationContext).thenReturn(webApplicationContext);
            // 以下代码是我的业务逻辑
            ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
            assertNotNull(ctx.getBean("answerInfo"));
        }
    }
}
英文:

You have to move the code inside the try. I hope this works for you:

class UserTest {
    @Mock
    WebApplicationContext webApplicationContext;

    @BeforeEach
     void setUp() throws Exception {
        MockitoAnnotations.openMocks(this);
    }

    @Test
     void test() {

//test Case Body
        try (MockedStatic&lt;ContextLoader&gt; dummy = Mockito.mockStatic(ContextLoader.class)) {
            Mockito.when(webApplicationContext.getBean(&quot;answerInfo&quot;)).thenReturn(new String());
            dummy.when(ContextLoader::getCurrentWebApplicationContext).thenReturn(webApplicationContext);
            //Below Code is my business logic
            ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
            assertNotNull( ctx.getBean(&quot;answerInfo&quot;));
        }
    }
}

答案2

得分: 0

我在一些研究和开发后尝试了这个,对我有用。
下面的代码对我起作用:

@Mock
static ServletContext servletContext;

@Mock
ContextLoader contextLoader;

@Mock
org.springframework.web.context.WebApplicationContext webApplicationContext;

@Mock
HttpServletRequest request;

private AutoCloseable closeable;

@BeforeAll
static void setUpBeforeClass() throws Exception {
    MockServletContext msc = new MockServletContext();
    msc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/test/config/spring/SpringBeansTest.xml");

    ServletContextListener listener = new ContextLoaderListener();
    ServletContextEvent event = new ServletContextEvent(msc);
    listener.contextInitialized(event);
}

@AfterAll
static void tearDownAfterClass() throws Exception {

}

@BeforeEach
void setUp() throws Exception {

    closeable = MockitoAnnotations.openMocks(this);

    Mockito.doReturn(Random.class).when(ctx).getBean(Mockito.anyString());

    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}

@AfterEach
void tearDown() throws Exception {
    closeable.close();
    closeable = null;
}
// 测试用例主体
try (MockedStatic<ContextLoader> dummy = Mockito.mockStatic(ContextLoader.class)) {
    dummy.when(() -> ContextLoader.getCurrentWebApplicationContext()).thenReturn(webApplicationContext);
}
英文:
I tried this after some RnD it&#39;s working for me 
The below code is worked for me:

@Mock
static ServletContext servletContext;

@Mock
ContextLoader contextLoader;

@Mock
org.springframework.web.context.WebApplicationContext webApplicationContext;

@Mock
HttpServletRequest request;

private AutoCloseable closeable;

@BeforeAll
static void setUpBeforeClass() throws Exception {
	MockServletContext msc = new MockServletContext();
	msc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, &quot;/test/config/spring/SpringBeansTest.xml&quot;);

	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(msc);
	listener.contextInitialized(event);
}

@AfterAll
static void tearDownAfterClass() throws Exception {

}

@BeforeEach
void setUp() throws Exception {

	closeable = MockitoAnnotations.openMocks(this);

	Mockito.doReturn(Random.class).when(ctx).getBean(Mockito.anyString());

	RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}

@AfterEach
void tearDown() throws Exception {
	closeable.close();
	closeable = null;
}
//test case body
try (MockedStatic&lt;ContextLoader&gt; dummy = Mockito.mockStatic(ContextLoader.class)) {
dummy.when(() -&gt; ContextLoader.getCurrentWebApplicationContext()).thenReturn(webApplicationContext);
}

huangapple
  • 本文由 发表于 2020年9月4日 13:59:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63735618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定