spring引导测试:为每个单元测试注入不同的资源

zy1mlcev  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(427)

我创建了一个@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));
  }
  ...
}

有人有什么建议吗?

zbwhf8kr

zbwhf8kr1#

SpringBootTest 注解为 @SpringExtension 它也解析方法参数的参数:

@Test
  public void test1(@Value("classpath:data/result1.json") Resource result1) {
    // ...
  }

  @Test
  public void test2(@Value("classpath:data/result2.json") Resource result2) {
    // ...
  }

相关问题