1.坐标修改
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.测试类测试
说明:@SpringBootTest()中的webEnvironment值的说明;
2.1不启动
说明:默认不启动,如下图所示。@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)。
java
package com.forever;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class WebTest {
@Test
void test(){
}
}
2.2默认端口
说明:@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
java
package com.forever;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class WebTest {
@Test
void test(){
}
}
2.3 随机端口
说明:随机端口,@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)。
java
package com.forever;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebTest {
@Test
void test(){
}
}
3.发送虚拟请求
3.1@AutoConfigureMockMvc
说明:开启虚拟mvc调用。
java
package com.forever;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟mvc调用
@AutoConfigureMockMvc
public class WebTest {
@Test
//形参写入或者上方写@Autowired;为方法注入资源。
void testWeb(@Autowired MockMvc mockMvc) throws Exception {
//发请求http://....../users;下面就是模拟的一个http请求,访问的是users
MockHttpServletRequestBuilder builder= MockMvcRequestBuilders.get("/users");
//执行对应的请求。
mockMvc.perform(builder);
}
}