美文网首页
spring framework test3种方式

spring framework test3种方式

作者: xiaotian是个混子 | 来源:发表于2019-09-29 10:31 被阅读0次

    来源>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);
        }
        
    }
    
    • @RunWith必须的,没什么好说的。
    • @ContextConfiguration是纯基于代码的测试环境,不会加载application.properties等环境信息,适用与配置无关的算法测试。
    • @SpringBootTest会加载配置信息,此处被测试的userRepository是与数据库打交道的,数据库信息都在application.yml中,所以此处我使用的@SpringBootTes注解。
    • 被@Test注解的是测试方法,可以一到多个。
      Junit只能进行单元测试,不能进行Web应用等集成测试,需要采用后面的测试方案。

    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"));
        }
        
    }
    
    • @WebAppConfiguration开启web上下文,需要注入WebApplicationContext。剩下的代码通俗易懂,不多介绍。
    开启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

    • Test方法中对用户和权限的注入有2种:@WithMockUser静态模拟一个用户;@WithUserDetails利用web自己的权限机制load一个用户。

    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。

    • <li>Provides support for different {@link #webEnvironment() webEnvironment} modes,
    • including the ability to start a fully running container listening on a
    • {@link WebEnvironment#DEFINED_PORT defined} or {@link WebEnvironment#RANDOM_PORT
    • random} port.</li>
    • <li>Registers a {@link org.springframework.boot.test.web.client.TestRestTemplate
    • TestRestTemplate} bean for use in web tests that are using a fully running container.
    • </li>

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

    相关文章

      网友评论

          本文标题:spring framework test3种方式

          本文链接:https://www.haomeiwen.com/subject/reldyctx.html