一,演示項目的相關信息
1,地址:
https://github.com/liuhongdi/servicetest
2,功能說明:演示給一個service生成測試文件
3,項目結構:如圖:
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,如何創建一個測試文件?
1,可以手動創建一個class文件
2,在intellij idea中可以快速創建一個test文件:
打開一個service類,在類名上執行: ctrl+shift+T
然后從彈出的窗口中選擇:
Create New Test
如圖:
三,java代碼說明
1,service/HelloService.java
package com.servicetest.demo.service; import org.springframework.stereotype.Service; @Service public class HelloService { public String sayHello(String name) { return "您好,"+name+"!"; } public int addTwo(int first,int second) { return first+second; } }
2,service/HelloServiceTest.java
package com.servicetest.demo.service; import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @DisplayName("測試HelloService") class HelloServiceTest { @Resource HelloService helloService; @BeforeAll static void initAll() { System.out.println("this is BeforeAll"); } @AfterAll static void endAll() { System.out.println("this is AfterAll"); } @BeforeEach public void initOne() { System.out.println("this is BeforeEach"); } @AfterEach public void endOne() { System.out.println("this is AfterEach"); } @Test @DisplayName("測試sayhello方法") void sayHello() { String hellostr = helloService.sayHello("老劉"); assertThat(hellostr, equalTo("您好,老劉!")); assertThat(hellostr, hasLength(6)); assertThat(hellostr, containsString("您好,")); } @ParameterizedTest @CsvSource({"1,2,3", "11,12,23", "33,100,133"}) @DisplayName("參數化測試") void addTwo(int first,int second,int sum) { int rest = helloService.addTwo(first,second); assertThat(rest, equalTo(sum)); } }
四,測試效果
五,查看spring boot的版本:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.3)