spring-boot之(12) test

  测试也是开发过程中很重要的环节,开发要保证交付的代码的可靠性,当你把接口交付给你其他开发人员,或者把功能交付给测试时,可靠性可不是随口一说,要保证可靠性,那么就需要对代码进行测试,代码最常用的测试就是单元测试,Spring Boot已经帮我们集成常用的单元测试,而且Spring-boot给我们集成好了很多很方便的测试工具,也提供了很多很好用的特性。

  • Spring-boot Test特性
  1. junit
  2. Spring Test & Spring Boot test
  3. AssertJ
  4. Hamcrest
  5. Mockito
  6. JSONassert
  7. JsonPath
  • 增加POM文件的依赖
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
  • 测试类使用SpringBootTest和RunWith注解修饰
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyTest {
   @Test
    public void exampleTest() {
        ...
    }
}

  正常编写测试用例一样,没有太大的区别

  • MOCK

  Spring Boot Test提供的Mock的特性,请参照官网学习,这里贴出官网一个普通Mock和Spring MVC的两个例子

import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.mock.mockito.*;
import org.springframework.test.context.junit4.*;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public 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");
    }

}

以上是普通的MOCK

import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.mock.mockito.*;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public 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 MVC 的MOCK

  • 参考资料

http://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#boot-features-testing

posted @ 2017-08-02 10:15  風之殤  阅读(123)  评论(0)    收藏  举报