Spring boot 测试

来源:互联网 发布:燕郊淘宝摄影棚 编辑:程序博客网 时间:2024/06/05 23:05

Spring Boot 测试

Spring boot提供了两个包来支持测试。

  • spring-boot-test: 包含测试的核心项

  • spring-boot-tets-autoconfigure: 用来支持测试的自动配置

使用Spring boot测试框架做集成测试integration testing,通常不需要真实部署你的应用,或者连接到其他的基础设施。

使用随机端口random ports来测试

如果你需要启动一个full running server,推荐使用random ports。每次测试都会随机选择一个端口用来测试。

如果测试需要做REST调用,可以@Autowire一个TestRestTemplate,它可以处理到运行server的链接。

@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)public class RandomPortExampleTests {    @Autowired    private TestRestTemplate restTemplate;    @Test    public void exampleTest() {        String body = this.restTemplate.getForObject("/", String.class);        assertThat(body).isEqualTo("Hello World");    }}

Mocking和Spying

Spring boot使用@MockBean@SpyBean来定义Mockito的mock和spy。

@RunWith(SpringRunner.class)@SpringBootTestpublic class MyTests {    @MockBean    private RemoteService remoteService;    @Autowired    private Reverser reverser;    @Test    public void exampleTest() {        // RemoteService has been injected into the reverser bean        given(this.remoteService.someCall()).willReturn("mock");        String reverse = reverser.reverseSomeCall();        assertThat(reverse).isEqualTo("kcom");    }}

JSON测试

使用@JsonTest,它将自动配置ObjectMapper@JsonComponentModulesGson等。

@RunWith(SpringRunner.class)@JsonTestpublic class MyJsonTests {    @Autowired    private JacksonTester<VehicleDetails> json;    @Test    public void testSerialize() throws Exception {        VehicleDetails details = new VehicleDetails("Honda", "Civic");        // Assert against a `.json` file in the same package as the test        assertThat(this.json.write(details)).isEqualToJson("expected.json");        // Or use JSON path based assertions        assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");        assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make")                .isEqualTo("Honda");    }    @Test    public void testDeserialize() throws Exception {        String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";        assertThat(this.json.parse(content))                .isEqualTo(new VehicleDetails("Ford", "Focus"));        assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");    }}

测试Spring MVC

测试Spring MVC controller可以使用@WebMvcTest,它会自动配置MockMvc,Mock MVC提供了一种强力的方式来测试MVC controllers,而不用启动一个完整的HTTP server。

@RunWith(SpringRunner.class)@SpringBootTest@AutoConfigureMockMvcpublic class MyControllerTests {    @Autowired    private MockMvc mvc;    @MockBean    private UserVehicleService userVehicleService;    @Test    public void testExample() throws Exception {        given(this.userVehicleService.getVehicleDetails("sboot"))                .willReturn(new VehicleDetails("Honda", "Civic"));        this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))                .andExpect(status().isOk()).andExpect(content().string("Honda Civic"));    }}

测试Spring JPA

@DataJpaTest可以用来测试JPA,默认它会使用一个嵌入式内存数据库。扫描@Entity类和JAP repository。Data JPA 测试还会默认注入一个TestEntityManager,它是标准EntityManager的替代品。

@RunWith(SpringRunner.class)@DataJpaTestpublic class ExampleRepositoryTests {    @Autowired    private TestEntityManager entityManager;    @Autowired    private UserRepository repository;    @Test    public void testExample() throws Exception {        this.entityManager.persist(new User("sboot", "1234"));        User user = this.repository.findByUsername("sboot");        assertThat(user.getUsername()).isEqualTo("sboot");        assertThat(user.getVin()).isEqualTo("1234");    }}

测试JDBC

使用@JdbcTest,类似于@DataJpaTest

@RunWith(SpringRunner.class)@JdbcTest@Transactional(propagation = Propagation.NOT_SUPPORTED)public class ExampleNonTransactionalTests {}