如何在IDEA中對於SpringBoot項目快速創建單元測試
創建測試用例
右鍵需要進行測試的方法,選擇GO TO然后選擇Test
點擊Create New Test
勾選需要創建單元測試的方法
然后點擊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這種錯誤都會過測試用例