这个类提供Spring测试上下文
需要借助TestContextManager来实现上下文注入。
TestContextManager 与@RunWith(SpringJUnit4ClassRunner.class) 效果一样
在spring-framework-reference中的介绍
参考如下java Code Examples for org.springframework.test.context.TestContextManager.prepareTestInstance
示例如下:
package com.netease.ey.pay.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestContextManager; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import javax.annotation.Resource; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @RunWith(Parameterized.class) @SpringBootTest @ContextConfiguration @AutoConfigureMockMvc public class PayControllerTest { private static final Logger logger = LoggerFactory.getLogger(PayControllerTest.class); @Resource private MockMvc mockMvc; private TestContextManager testContextManager; @Before public void setUp() throws Exception { testContextManager = new TestContextManager(getClass()); testContextManager.prepareTestInstance(this); } @Parameterized.Parameters(name = "{index}:orderId:{0}") public static Object[] data() { return new Object[] { "1","7"}; } @Parameterized.Parameter // first data value (0) is default public /* 不能为 private */ String orderId; @Test public void transfer() throws Exception { String response = mockMvc.perform(MockMvcRequestBuilders.post("/pay/transfer") .param("orderId", orderId)) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(print()) //打印出请求和相应的内容 .andReturn().getResponse().getContentAsString(); logger.info("返回值{}",response); } }