spring framework test3种方式

2019-09-29  本文已影响0人  xiaotian是个混子

来源>https://blog.csdn.net/yejingtao703/article/details/77545300

微服务中Spring boot的分布数以百计,这么多的服务结点如果依赖人工测试将会是一场灾难,所以单个的boot服务必须具有单元测试甚至更负责的集成测试的能力。毕竟在微服务框架中,我们更多的精力会花费在服务架构上,而不是单个的服务能力上。

Spring boot提供了1种单元测试和2种web应用测试。

单元测试:

SpringJUnit4ClassRunner可以在基于JUnit的应用程序测试里加载Spring应用程序上下文进行单元测试。

Pom依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

测试代码

 @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=com.mydemo.Application.class)
//@ContextConfiguration(classes=com.mydemo.Application.class)//此注解只适用不依赖于环境配置的单元测试
public class UserRepositoryTester {
    
    @Autowired
    private UserRepository userRepository;
    
    @Test
    public void serviceTest() {
        SysUser user = new SysUser();
        user.setUserName("fortest");
        user.setPassword((new BCryptPasswordEncoder()).encode("password123"));
        SysUser findingUser = userRepository.findByUserName(user.getUserName());
        Assert.assertNull("User fortest shoud be null", findingUser);
        
        userRepository.save(user);
        findingUser = userRepository.findByUserName(user.getUserName());
        Assert.assertNotNull("User fortest shoud be added", findingUser);
        
        userRepository.delete(findingUser.getId());
        findingUser = userRepository.findByUserName(user.getUserName());
        Assert.assertNull("User fortest shoud be deleted", findingUser);
    }
    
}

Web测试:

Spring Mock MVC:能在一个近似真实的模拟Servlet容器里测试控制器,而不用实际启动应用服务器。

Mock也要分是否启用Security,我们分别做了2套测试代码。

不开启Security的方式:
 @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=com.mydemo.Application.class)
@WebAppConfiguration//开启Web上下文 测试
public class NoSecurityMockTester {
    
    @Autowired
    private WebApplicationContext webContext;//注入WebApplicationContext 
    
    private MockMvc mockMvc;
    
    /**
     * setupMockMvc()方法上添加了JUnit的@Before注解,表明它应该在测试方法之前执行。
     */
    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webContext).build();
    }
    
    @Test
    public void helloPage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("hello world"));
    }
    
}
开启Security的方式:

Pom需要增加一个依赖

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = com.mydemo.Application.class)
@WebAppConfiguration // 开启Web上下文 测试
public class WithSecurityMockTester {
 
    @Autowired
    private WebApplicationContext webContext;// 注入WebApplicationContext
 
    private MockMvc mockMvc;
 
    /**
     * setupMockMvc()方法上添加了JUnit的@Before注解,表明它应该在测试方法之前执行。
     */
    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webContext).apply(springSecurity()).build();
    }
 
    @Test
    public void helloPage() throws Exception {
        mockMvc.perform(get("/hello")).andExpect(status().isOk()).andExpect(content().string("hello world"));
    }
 
    /**
     * 没有权限会被重定向到登陆页面
     * 
     * @throws Exception
     */
    @Test
    public void roleTestMothedAPage() throws Exception {
        mockMvc.perform(get("/forRoleA")).andExpect(status().is3xxRedirection())
                .andExpect(header().string("Location", "http://localhost/login"));
    }
 
    @Test
    @WithMockUser(username = "userb", password = "userb123", authorities = "authority_b")
    public void roleTestMothedBPage() throws Exception {
        mockMvc.perform(get("/forRoleB")).andExpect(status().isOk()).andExpect(content().string("Role B Successful"));
    }
 
    @Test
    @WithUserDetails(value = "userab")
    public void roleTestMothedABPage() throws Exception {
        mockMvc.perform(get("/forRoleB")).andExpect(status().isOk()).andExpect(content().string("Role B Successful"));
        mockMvc.perform(get("/forRoleA")).andExpect(status().isOk()).andExpect(content().string("Role A Successful"));
    }
 
}

这里代码稍作调整,导入静态方法的方式使代码更简洁。

Mock初始化不同点springSecurity(),开启security

selenium集成测试:在嵌入式Servlet容器(Tomcat、Jetty)里启动应用程序,在真正的应用服务器里执行测试。

Pom添加依赖

<dependency>
     <groupId>org.seleniumhq.selenium</groupId>
     <artifactId>selenium-server</artifactId>
      <version>3.0.0-beta4</version>
</dependency>

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = com.mydemo.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// @WebIntegrationTest
public class WebIntegrationTester {
 
    @Value("${local.server.port}")
    private int port;
 
    @Test
    public void roleTestMothedBPage() throws Exception {
        System.setProperty("webdriver.firefox.bin", "C:\\Mozilla Firefox\\firefox.exe");
        FirefoxDriver webDriver = new FirefoxDriver();
        webDriver.manage().window().maximize();
        webDriver.get("http://127.0.0.1:" + port + "/forRoleB");
        webDriver.findElementByName("username").sendKeys("userab");
        webDriver.findElementByName("password").sendKeys("userab123");
        webDriver.findElementByName("submit").click();
        System.out.println(webDriver.getPageSource());
    }
 
}

这里吐糟一下,网上各种资料介绍要添加@WebIntegrationTest注解,但是此注解在1.5以后就弃用了,网上也没有资料,最终看1.5的源码才发现要通过配置@SpringBootTest注解的一个enum来真正启动web。

这两种web测试方式各有利弊:mock方式更轻量,嵌入方式更真实,你可以看到你的浏览器跟中了魔一样自动操作。
Ps:Web-Flux 和Web测试是有许多区别的
参考

上一篇下一篇

猜你喜欢

热点阅读