springboot之SpringBoot单元测试

SpringBoot单元测试

spring单元测试

之前在spring项目中使用单元测试时是使用注解@RunWith(SpringJUnit4ClassRunner.class)来进行的


java

代码解读

复制代码

@RunWith(SpringJUnit4ClassRunner.class)// 通过自动织入从应用程序上下文向测试本身注入bean @WebAppConfiguration // 指定web环境 @ContextConfiguration(locations = { // 指定配置文件 "classpath*:springmvc.xml" })

使用@WebAppConfiguration注解之后还可以注入WebApplicationContext环境


java

代码解读

复制代码

@Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setup(){ mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); }

MockMvc

我们可以使用MockMvc来进行模拟请求


json

代码解读

复制代码

@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依赖来进行测试


xml

代码解读

复制代码

<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <version>5.1.5.RELEASE</version> <scope>test</scope> </dependency>

在进行开启支持springSecurity


java

代码解读

复制代码

@Before public void setup(){ mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .apply(SecurityMockMvcConfigurers.springSecurity()) .build(); }

在写单元测试方法时,可以使用@WithMockUser来设置用户


java

代码解读

复制代码

@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)注解


java

代码解读

复制代码

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); }

示例


java

代码解读

复制代码

@RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired private CustomConfig config; @Test public void testProfile() { System.out.println(config.getName()); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值