-
在测试类上的@ContextConfiguration注解需要指定spring的配置文件,由于我们使用的是java配置,所以这里传递我们的配置类,记住是spring的配置类,而不是web的配置类(注:web的配置我们是通过模拟的)。
-
因为controller,component等都是使用注解来,所以我们的@ContextConfiguration使用的是直接来加载的。因此在他的属性中,配置一个loader。同时由于是web的,所以使用AnnotationConfigWebContextLoader。
-
由于需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
1
2
3
4
|
@RunWith
(Parameterized.
class
)
@ContextConfiguration
(classes = { WebMVCConfiguration.
class
}, loader = AnnotationConfigWebContextLoader.
class
)
@WebAppConfiguration
public
class
ControllerTest
|
1
2
3
4
5
6
7
|
@Controller
public
class
TestController {
@RequestMapping
(value =
"/test"
, method = RequestMethod.GET)
public
@ResponseBody
String test(String name) {
return
name;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// parameters
private
String name;
private
String result;
public
ControllerTest(String name, String result) {
this
.name = name;
this
.result = result;
}
@Parameters
public
static
Collection<String[]> data() {
return
Arrays.asList(
new
String[][] { {
"Troy"
,
"Troy"
},
{
"Young"
,
"Young"
} });
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
private
TestContextManager testContextManager;
private
MockMvc mockMvc;
@Autowired
private
WebApplicationContext wac;
@Before
public
void
setUp()
throws
Exception {
testContextManager =
new
TestContextManager(getClass());
testContextManager.prepareTestInstance(
this
);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
|
1
2
3
4
5
6
7
|
@Test
public
void
test()
throws
Exception {
MvcResult rs = mockMvc.perform(
MockMvcRequestBuilders.get(
"/test?name="
+ name)).andReturn();
assertEquals(
"name is not correct"
, result,
new
String(rs.getResponse()
.getContentAsByteArray()));
}
|