首页 > 编程语言 >学会spring boot 的这些,编程瞬间变得简单了,效率也提高了!

学会spring boot 的这些,编程瞬间变得简单了,效率也提高了!

时间:2024-06-11 10:02:28浏览次数:14  
标签:断言 spring 编程 boot Assert Person Act new Arrange

在Spring Boot应用中,断言主要用于测试环境中验证代码行为是否符合预期。虽然Spring Boot自身不直接包含断言库,但通常我们会使用JUnit(一个广泛应用于Java的单元测试框架)来进行测试,其中包含了丰富的断言方法来帮助我们进行各种条件验证。下面通过一些具体的示例来详细说明如何在Spring Boot应用中使用JUnit进行断言。

断言

从Spring Boot 2.x开始,推荐使用JUnit 5作为测试框架。JUnit 5提供了强大的断言API,让测试更加灵活和强大。

1. 基础数值断言

import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
  
    @Test    void additionShouldReturnCorrectSum() {
          // Arrange        Calculator calculator = new Calculator();                // Act        int result = calculator.add(3, 4);                // Assert        assertEquals(7, result, "3加上4应该等于7");    }}
2. 对象断言:比较对象内容
@Testvoid equalityOfObjects() {
      // Arrange    Person person1 = new Person("Alice", 30);    Person person2 = new Person("Alice", 30);        // Act (in this case, no action needed before asserting)        // Assert    assertEquals(person1, person2, "两个Person对象应该是相等的");}

注意,为了使assertEquals能正确比较自定义对象,需要在Person类中重写equals()hashCode()方法。

3. 异常断言
@Testvoid divisionByZeroShouldThrowException() {
      // Arrange    Calculator calculator = new Calculator();        // Act & Assert    assertThrows(ArithmeticException.class, () -> calculator.divide(10, 0),            "除以0应该抛出ArithmeticException");}

4. 集合和数组断言​​​​​​
@Testvoid listContentShouldMatch() {
      // Arrange    List<String> expected = Arrays.asList("one", "two", "three");    List<String> actual = service.getWords();        // Act (no action needed here)        // Assert    assertEquals(expected, actual, "列表内容应匹配");}

对于数组,使用assertArrayEquals()方法进行比较。

5. 布尔断言​​​​​​​
@Testvoid isAdultShouldReturnTrueForAgeOver18() {
      // Arrange    Person person = new Person("Bob", 20);        // Act    boolean isAdult = person.isAdult();        // Assert    assertTrue(isAdult, "20岁应该是成年人");}

异步测试中的断言

在现代应用开发中,异步编程模型变得日益重要,尤其是在处理I/O密集型操作或与外部服务交互时。Spring Boot应用也不例外,经常需要对异步逻辑进行测试。JUnit 5为此提供了一系列的扩展来支持异步测试,主要通过Assertions.assertTimeoutAssertions.assertAsync方法来实现。

异步执行时长断言​​​​​​​
@Testvoid asyncOperationShouldCompleteInTime() {
      // Arrange    AsyncService asyncService = new AsyncService();        // Act & Assert    assertTimeout(Duration.ofMillis(100), () ->         asyncService.performLongRunningTask().get()    , "异步

标签:断言,spring,编程,boot,Assert,Person,Act,new,Arrange
From: https://blog.csdn.net/qq_19812507/article/details/139590356

相关文章