Spring

SpringBoot 测试-Web层

2018-01-07  本文已影响587人  当当一丢丢

项目环境

SpringBoot test 涉及的几个方面

前提

代码

pom 依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
Controller
@RestController
@RequestMapping
public class BookController {
    @RequestMapping("/books")
    public String book() {
        System.out.println("controller");
        return "book";
    }
}
Test1 引入Spring上下文,但不启动tomcat
@RunWith(SpringRunner.class)
@SpringBootTest  //引入Spring上下文 -> 上下文中的 bean 可用,自动注入
public class BookControllerTest {
    
    @Autowired
    private BookController bookController;  //自动注入
    
    @Test
    public void testControllerExists() {
        Assert.assertNotNull(bookController);
    }
    
}

解释

Test2 引入Spring上下文,且启动Tomcat 模拟生产环境,接收Http请求
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)  //RANDOM_PORT 启动Tomcat
public class BookControllerTest {
    
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate testRestTemplate;
    
    @Test
    public void testBook() {
        Assert.assertEquals(this.testRestTemplate.getForObject("http://localhost:" + port + "/books", String.class), "book");
    }
    
}

解释

Test3 引入Spring上下文,不启动Tomcat, 由 MockMVC 发送请求
@RunWith(SpringRunner.class)
@SpringBootTest  
@AutoConfigureMockMvc //启动自动配置MockMVC
public class BookControllerTest {

    @Autowired
    private MockMvc mockMvc; //只需 autowire
    
    @Test
    public void testBook2() throws Exception {
        this.mockMvc.perform(get("/books"))
                .andExpect(status().is(200))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(content().string("book"))
                .andReturn();  
    }
    
}

解释

Test4 只引入Web 层 的Spring上下文,不启动Tomcat, 由 MockMVC 发送请求
@RunWith(SpringRunner.class)
//@SpringBootTest  //full Spring application context
@WebMvcTest
public class BookControllerTest {

    @Autowired
    private MockMvc mockMvc; //只需 autowire
    
    @Autowired  //可以正常注入
    private BookController bookController; 

    //@Autowired //另建@Service BookService 类,编译通过,但test运行时异常,不能注入 web 层以外的 bean
    private BookService bookService;
    
    @Test
    public void testBook2() throws Exception {
        this.mockMvc.perform(get("/books"))
                .andExpect(status().is(200))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(content().string("book"))
                .andReturn();  
    }
    
}

解释

Test5 只引入Web 层 特定Controller 的Spring上下文,不启动Tomcat, 由 MockMVC 发送请求
@RunWith(SpringRunner.class)
@WebMvcTest(BookControler.class) //明确指定引入的 哪个web controller 上下文
public class BookControllerTest {

    @Autowired
    private MockMvc mockMvc; //只需 autowire
    
    @Autowired  //可以正常注入
    private BookController bookController; 

    //@Autowired //另建@RestController BookController2 类,编译通过,但test运行时异常,不能注入 Book Controller以外的 bean
    private BookController2 BookController2;
    
    @Test
    public void testBook2() throws Exception {
        this.mockMvc.perform(get("/books"))
                .andExpect(status().is(200))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(content().string("book"))
                .andReturn();  
    }
    
}

解释

Test6 前5个例子都未涉及Controller的依赖问题,现在 controller 依赖 service

添加service

@Service
public class BookService {  //添加 Service 层
    public String addBook() {
        return "book";
    }
}

更改Controller,注入 service

@RestController
@RequestMapping
public class BookController {

    @Autowired
    private BookService bookService; //注入 依赖 service bean

    @RequestMapping("/books")
    public String addBook() {
        return bookService.addBook();
    }
}

Test 6-1 web layer application context

@RunWith(SpringRunner.class)
@WebMvcTest(BookControler.class) //明确指定引入的 哪个web controller 上下文
public class BookControllerTest {

    @Autowired
    private MockMvc mockMvc; //只需 autowire
    
    @MockBean //mock 伪造 一个 bookService bean 否则,上下文环境中不存在,因为指定了 @WebMvcTest,否则应用启动异常
    private BookService bookService;
    
    @Autowired  //可以正常注入
    private BookController bookController; 

    
    @Test
    public void testBook2() throws Exception {
        //因为是mock出的bookService
        //同时为了将测试范围限定在 controller 层,所以将 service 层的调用固定化
        //相当于 service 层的逻辑没有测试直接返回一个假定的结果
        when(bookService.addBook()).thenReturn("book");
        this.mockMvc.perform(get("/books"))
                .andExpect(status().is(200))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(content().string("book"))
                .andReturn();  
    }
    
}

Test 6-2 full Spring application context

@RunWith(SpringRunner.class)
@SpringBootTest  // 开启 full Spring application context
@AutoConfigureMockMvc //启动自动配置MockMVC
public class BookControllerTest {

    @Autowired
    private MockMvc mockMvc; //只需 autowire
    
    //@MockBean //不需要伪造 一个 bookService bean 因为上下文环境中存在,因为指定了 @SpringBootTest
    //private BookService bookService;
    
    @Autowired  //可以正常注入
    private BookController bookController; 

    
    @Test
    public void testBook2() throws Exception {
        this.mockMvc.perform(get("/books"))
                .andExpect(status().is(200))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(content().string("book"))
                .andReturn();  
    }
    
}

解释

参考:
上一篇 下一篇

猜你喜欢

热点阅读