SpringBoot單元測試
spring單元測試
之前在spring項目中使用單元測試時是使用注解@RunWith(SpringJUnit4ClassRunner.class)來進行的
@RunWith(SpringJUnit4ClassRunner.class)//?通過自動織入從應用程序上下文向測試本身注入bean
@WebAppConfiguration?//?指定web環境
@ContextConfiguration(locations?=?{?//?指定配置文件
????????"classpath*:springmvc.xml"
})
使用@WebAppConfiguration注解之后還可以注入WebApplicationContext環境
@Autowired
private?WebApplicationContext?webApplicationContext;
private?MockMvc?mockMvc;
@Before
public?void?setup(){
????mockMvc?=?MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
MockMvc
我們可以使用MockMvc來進行模擬請求
@Test
public?void?test()?throws?Exception?{
????MockHttpServletResponse?response?=?mockMvc.perform(MockMvcRequestBuilders.get("/json/testJson"))
????????????.andExpect(MockMvcResultMatchers.status().isOk())
????????????.andReturn().getResponse();
????System.out.println(response.getContentAsString());
}
web安全測試
我們項目中經常會使用spring-security來進行權限,這就給我們的測試帶來了麻煩,可以使用spring-security-test依賴來進行測試
<dependency>
????????????<groupId>org.springframework.security</groupId>
????????????<artifactId>spring-security-test</artifactId>
????????????<version>5.1.5.RELEASE</version>
????????????<scope>test</scope>
????????</dependency>
在進行開啟支持springSecurity
@Before
public?void?setup(){
????mockMvc?=?MockMvcBuilders
????????????.webAppContextSetup(webApplicationContext)
????????????.apply(SecurityMockMvcConfigurers.springSecurity())
????????????.build();
}
在寫單元測試方法時,可以使用@WithMockUser來設置用戶
@Test
@WithMockUser(username?=?"root",password?=?"123456",roles?=?"ADMIN")
public?void?testSecurity()?throws?Exception?{
????MockHttpServletResponse?response?=?mockMvc.perform(MockMvcRequestBuilders.get("/json/testJson"))
????????????.andExpect(MockMvcResultMatchers.status().isOk())
????????????.andReturn().getResponse();
????System.out.println(response.getContentAsString());
}
然后使用測試的UserDetails來進行用戶驗證@WithUserDetails("root")
springboot單元測試
springboot中可以使用@SpringBootTest來進行單元測試,其中設置webEnvironment可以來定義運行模式,并在測試用例上使用@RunWith(SpringRunner.class)注解
enum?WebEnvironment?{
???//?加載WebApplicationContext,并提供一個mock?servlet環境,使用該模式內嵌的servlet容器不會啟動
???MOCK(false),
???//?加載EmbeddedWebApplicationContext,并提供一個真實的servlet環境,內嵌servlet容器啟動,并監聽一個隨機端口
???RANDOM_PORT(true),
???//?加載EmbeddedWebApplicationContext,并提供一個真實的servlet環境,內嵌servlet容器啟動,并監聽一個定義好的接口
???DEFINED_PORT(true),
??//?使用SpringApplication加載一個ApplicationContext,但不提供servlet環境
???NONE(false);
}
示例
@RunWith(SpringRunner.class)
@SpringBootTest
public?class?DemoApplicationTests?{
???@Autowired
???private?CustomConfig?config;
???@Test
???public?void?testProfile()?{
??????System.out.println(config.getName());
???}
}
https://zhhll.icu/2022/框架/springboot/基礎/17.springboot單元測試/
本文由 mdnice 多平臺發布