我创建了一个@springboottest注解类来测试rest端点的http响应。
我将每个httpjson响应与资源的内容进行比较。
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleApplicationTests {
@Autowired
private MockMvc mockMvc;
@Value("classpath:data/result1.json")
private Resource result1;
@Value("classpath:data/result2.json")
private Resource result2;
@Test
public void test1() {
mockMvc.perform(MockMvcRequestBuilders.
get("/api/persons")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().json(asString(result1)));
}
@Test
public void test2() {
mockMvc.perform(MockMvcRequestBuilders.
get("/api/persons/1")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().json(asString(result2)));
}
...
private static String asString(Resource resource) {
try {
return IOUtils.toString(resource.getInputStream());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
我想知道是否有一种更优雅的方法在每个测试级别注入资源。
我知道我可以用 ResourceLoader
要为每个测试加载资源,请执行以下操作:
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleApplicationTests {
@Autowired
private ResourceLoader resourceLoader = null;
@Test
public void test1() {
String result = asString(resourceLoader.getResource("classpath:data/result1.json");
mockMvc.perform(MockMvcRequestBuilders.
get("/api/persons")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().json(result));
}
...
}
但是我想知道是否有一个注解允许为每个测试加载一个资源。如下所示:
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleApplicationTests {
@Test
@TestResource("classpath:data/result1.json")
public void test1(Resource result) {
mockMvc.perform(MockMvcRequestBuilders.
get("/api/persons")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().json(result));
}
...
}
有人有什么建议吗?
1条答案
按热度按时间zbwhf8kr1#
SpringBootTest
注解为@SpringExtension
它也解析方法参数的参数: