学了springboot才知道以前的一大堆配置是多么的痛。废话不多说,将学习springboot过程中遇到的问题总结下
已知个人有两个spring boot的启动类
一、单元测试
package com.mkydy.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes= com.mkydy.springboot.SpringBootFastjsonApplication.class)
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void exampleTest() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("\"Greetings from Spring Boot!\""));
}
}
1.和官网示例不同的是,@SpringBootTest注解需要配置classes,指定你自定义的启动类(是我有两个启动类的原因?)
另外,注意导入三个静态方法。不然看了其它教程会一脸懵逼。
2.string()中的字符串需要加转意字符,因为body的内容是纯字符串没有双引号包裹。
二、集成测试
package com.mkydy.springboot;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Spring Boot 集成测试
* @author Mkydy
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,classes=com.mkydy.springboot.SpringBootFastjsonApplication.class)
@AutoConfigureWebTestClient
public class HelloWorldTest {
private URL base;
@LocalServerPort
private int port;
@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);
assert (response.getBody().equals("Greetings from Spring Boot!"));
}
}
和官网不同的是需要加上@AutoConfigureWebTestClient注解,不然会报错,其次,还需要引入webflux jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>
var code = "979cb6e2-280c-4c7b-9501-71e946ea17f5"
参考文章: