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

  • 相关阅读:
    [非专业翻译] Mapster
    Js 之TreeGrid使用
    Java 之无限级分类
    Layui 之layedit动态赋值
    Java 之配置修改代码不重启服务器
    Java 之QueryRunner实现增删改查
    Java 之c3p0连接池 + dbutils例子
    PHP 之阿里云短信插件
    Java 之数据库工具类
    Java 之myEclipse破解代码
  • 原文地址:https://www.cnblogs.com/linkstar/p/7562172.html
Copyright © 2011-2022 走看看