springboot junit test


依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>


<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

 

 

1.注解列表

  • @RunWith:標識為JUnit的運行環境;
  • @SpringBootTest:獲取啟動類、加載配置,確定裝載Spring Boot;
  • @Test:聲明需要測試的方法;
  • @BeforeClass:針對所有測試,只執行一次,且必須為static void;
  • @AfterClass:針對所有測試,只執行一次,且必須為static void;
  • @Before:每個測試方法前都會執行的方法;
  • @After:每個測試方法前都會執行的方法;
  • @Ignore:忽略方法;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //不必顯示指明啟動類等
@ActiveProfiles("xx")
@Transactional
@Slf4j  // 日志

 

 

 創建測試類方法:https://www.w3cschool.cn/intellij_idea_doc/intellij_idea_doc-mrn42f9j.html

右鍵 >>>GO TO  >>> TEST

2.Assert斷言

  • Assert.assertEquals 對比兩個值相等
  • Assert.assertNotEquals 對比兩個值不相等
  • Assert.assertSame 對比兩個對象的引用相等
  • Assert.assertArrayEquals 對比兩個數組相等
  • Assert.assertTrue 驗證返回是否為真
  • Assert.assertFlase 驗證返回是否為假
  • Assert.assertNull 驗證null
  • Assert.assertNotNull 驗證非null

 

3.Web模擬測試

 

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestServiceImplTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @DisplayName("接口描述,展示測試方法")
    @Test
    public void test() {
        restTemplate.getForObject(xx, xx)
    }

} 

 

4.數據庫測試

給測試類上添加“@Transactional”,這樣既可以測試數據操作方法,又不會污染數據庫了。

 

Springboot測試類之@RunWith注解

junit5測試:Java單元測試之JUnit 5快速上手

Spring Boot(十二)單元測試JUnit

https://www.cnblogs.com/vipstone/p/9908545.html

JUnit基本注解使用

https://www.jianshu.com/p/921282034c5d

https://blog.csdn.net/qq_42651904/article/details/89945495

 

5.cron表達式

* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小時,取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
          另外:1表示星期天,2表示星期一。
* 第7為,年份,可以留空,取值1970-2099


(*)星號:可以理解為每的意思,每秒,每分,每天,每月,每年...
(?)問號:問號只能出現在日期和星期這兩個位置。
(-)減號:表達一個范圍,如在小時字段中使用“10-12”,則表示從10到12點,即10,11,12
(,)逗號:表達一個列表值,如在星期字段中使用“1,2,4”,則表示星期一,星期二,星期四
(/)斜杠:如:x/y,x是開始值,y是步長,比如在第一位(秒) 0/15就是,從0秒開始,每15秒,最后就是0,15,30,45,60    另:*/y,等同於0/y

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM