Spring Boot单元测试之分层测试与整体测试

单元测试Case

单元测试1:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerApplicationTest {
    @Autowired    
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Spring Boot!")));
    }
}

单元测试2:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo("Spring Boot!")));
    }
}

单元测试3:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

@LocalServerPort
private int port;

private URL base;

@Autowired
private TestRestTemplate template;

@Before
public void setUp() throws Exception {
    this.base = new URL("http://localhost:" + port + "/");
}

@Test
public void getHello() throws Exception {
    ResponseEntity<String> response = template.getForEntity(base.toString(),
            String.class);
    assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}

这三个测试用例实现类似的功能,但是它们之间有什么区别呢?

区别与分析

第一个是仅仅扫描Controller的代码进行执行,如果Controller中有相关依赖则需要Mock,并进行调用功能的提前赋值,方可正常进行测试。

第二个则是启动了整个Application context,从而调用Controller层的功能进行触发,其底层功能依赖,比如Service,则无需进行依赖。

第三个功能类似第二种方式,区别在于调用HTTP服务的方式不同,这里使用TestRestTemplate的实例来进行的。

其他注解

@DataJpaTest
@JsonTest
@WebMvcTest
@RestClientTests
@JdbcTest
@WebFluxTest

总结

一般情况基于当个层的测试会比较隔离,但是需要自行注入依赖。而基于Spring Boot Test则自动加载了依赖,会比较容易。

参考资料

  1. https://stackoverflow.com/questions/39865596/difference-between-using-mockmvc-with-springboottest-and-using-webmvctest
发布了478 篇原创文章 · 获赞 804 · 访问量 433万+

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/88879164