Junit5:测试仅使用构建器模式而不使用任何设置器的对象的验证方法

问题描述 投票:0回答:1

我有域聚合

Employee
,它使用构建器模式在对象构造期间设置其字段。它有各种改变状态的生命周期方法,但没有直接的设置器。

它还有一个 validate() 方法,用于检查构建器设置的字段上的某些条件,因此可能会因多种原因失败(抛出异常)。

聚合有点像下面这样:

public class Employee {

  private String field1;
  private String field2:

  //say 10 fields

  public static Builder builder() {
    return new Builder();
  }

  public static Builder() {
    // builder fields and methods
  }

  //public lifecycle methods

  public void validate() {
    if (field1 == null) {
       //throw custom exception
    }
    if (field2 == null) {
       //throw custom exception
    }
    // More condition checks on fields (not all are null checks)
  } 
}

现在我的测试班安排如下:

public class EmployeeTest {
     
    @Test
    public void givenNewEmployee_IfField1IsMissing_thenThrowsException() {
      
      //Setup
      Employee testEmployee = Employee.builder()
                               .field2(nonNullValue)
                               //other fields
                               .build();

 
      Assertions.assertThrows(CustomException.class, testEmployee::validate);
    }

     @Test
    public void givenNewEmployee_IfField2IsMissing_thenThrowsException() {
      
      //Setup
      Employee testEmployee = Employee.builder()
                               .field1(nonNullValue)
                               //other fields
                               .build();

      //Test
      Assertions.assertThrows(CustomException.class, testEmployee::validate);
    }
 
}

在上面,对于每个测试用例,我必须构建整个 Employee 测试对象

testEmployee
,除了
build()
方法中的一个字段。这使得我的测试用例变得笨拙并且需要很多行代码。

我的问题是:

有没有一种方法可以用来设置

testEmployee
对象一次,然后在每个测试用例中将各个字段设置为 null,以便我的测试简洁并且不需要构建整个
testEmployee

我知道用于设置测试的

@BeforeAll
@BeforeEach
注释。但由于我的
Employee
类不提供任何设置器,我无法在
testEmployee
中设置一个有效的
@BeforeEach
,然后在每个测试用例中将各个字段设置为 null。所以我需要替代方案(如果有)。

java unit-testing junit junit4 junit5
1个回答
0
投票

@BeforeEach
中创建构建器并填充所有字段。然后储存起来。

在每个测试中将字段设置为

null
,然后构建并验证。

或者您可以创建

toBuilder
方法。

© www.soinside.com 2019 - 2024. All rights reserved.