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

  • 相关阅读:
    北京礼品在线盛大发布
    医生专用手机(智能、导航、名片扫描、医生掌上电子助手)
    医生专用手机/PDA
    DEDE 栏目内容 {dede:field.content/} 输入值不保存解决方法
    礼至上礼品策划中心
    ASP.NET WAP开发
    国内唯一具有智能礼品推荐系统
    招聘发帖兼职人员帖酬高达0.5元/条http://li010.com
    软件文档知多少?
    地高人柳州地区高中校友大联盟 地高校友录,聚会活动,今日地高,母校追忆,校友今朝,职场生涯
  • 原文地址:https://www.cnblogs.com/linkstar/p/7562172.html
Copyright © 2011-2022 走看看