zoukankan      html  css  js  c++  java
  • IDEA中SpringBoot项目快速创建单元测试

    如何在IDEA中对于SpringBoot项目快速创建单元测试

    创建测试用例

    image

    右键需要进行测试的方法,选择GO TO然后选择Test

    image

    点击Create New Test

    image

    勾选需要创建单元测试的方法

    然后点击OK就直接创建完成了。

    修改测试用例

    在类上面加上注解

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    然后在下面注入需要测试的类然后在方法里面使用,使用方法和普通的单元测试一样
    如果测试的是service
    demo如下
    package com.example.demo;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    public class HelloServiceTest {
    
        @Autowired
        private HelloService helloService;
    
        @Test
        public void hello(){
            helloService.hello();
        }
    
    }

    如果测试的是controller

    需要加入@AutoConfigureMockMvc的注解

    那么demo如下

    package com.example.demo;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    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.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class HelloControllerTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void hello() throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                    .andExpect(MockMvcResultMatchers.status().isOk());
        }
    
    }

    其中对于MockMvc的使用可以自己研究一下,里面有很多测试使用的东西,这边只是举个例子,只要访问是200不是404这种错误都会过测试用例

  • 相关阅读:
    jmeter的基本功能使用详解
    服务器资源监控插件(jmeter)
    前端技术之--CSS
    前端技术之--HTML
    TCP/IP基础知识
    TCP/IP、Http的区别
    关于性能调优
    如何修改Docker已运行实例的端口映射
    Mysql 主从同步配置
    Presto的基本概念
  • 原文地址:https://www.cnblogs.com/linkstar/p/7562172.html
Copyright © 2011-2022 走看看