IDEA中SpringBoot项目快速创建单元测试_Java_weixin_34268169的博客-CSDN博客

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


Original url: Access
Created at: 2020-04-15 16:35:52
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论