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这种错误都会过测试用例

  • 相关阅读:
    HttpUtils 用于进行网络请求的工具类
    Java 身份证工具类
    MD5加密Java工具类
    Nginx配置文件详细说明
    java统计abacbacdadbc中的每个字母出现的次数,输出格式是:a(4)b(3)c(3)d(2)
    mysql查询今天,昨天,近7天,近30天,本月,上一月数据的SQL
    Java随机生成常用汉字验证码
    Google Kaptcha验证码的使用
    Linux查看CPU和内存使用情况
    myql导入导出命令
  • 原文地址:https://www.cnblogs.com/linkstar/p/7562172.html
Copyright © 2011-2022 走看看