Spring 启动测试:为每个单元测试注入不同的资源

Spring Boot Test: Inject different Resources for each unit tests

我创建了一个带@SpringBootTest 注释的 class 来测试 REST 端点的 HTTP 响应。

我将每个 HTTP JSON 响应与资源的内容进行比较。

@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));
  }
  ...
}

有人有什么建议吗?

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

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

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