我想问的是,这两种方法中如何使用“verify”,我在每种方法中都添加了它的用法,但我不确定是否正确,我无法处理这个过程。
我该怎么解决呢?
这是在JUnit测试方法中定义验证的最佳方式。
下面是我的代码片段。
@DataJpaTest
public class EmployeeRespositoryTests {
private EmployeeRepository employeeRepository;
@BeforeEach
void setUp() {
employeeRepository = mock(EmployeeRepository.class);
}
@Test
public void givenEmployeeObject_whenSave_thenReturnSavedEmployee(){
//given - precondition or setup
Employee employee = Employee.builder()
.firstName("Name 1")
.lastName("Surname 1")
.email("user1@a,com")
.build();
// when - action or the behaviour that we are going test
Employee savedEmployee = employeeRepository.save(employee);
// then - verify the output
assertThat(savedEmployee).isNotNull();
assertThat(savedEmployee.getId()).isGreaterThan(0);
// HERE IS MY CODE
verify(employeeRepository, times(1)).save(user);
}
// JUnit test for get all employees operation
@DisplayName("JUnit test for get all employees operation")
@Test
public void givenEmployeesList_whenFindAll_thenEmployeesList(){
// given - precondition or setup
Employee employee = Employee.builder()
.firstName("Name 1")
.lastName("Surname 1")
.email("user1@a,com")
.build();
Employee employee1 = Employee.builder()
.firstName("Name 2")
.lastName("Surname 2")
.email("user2@a,com")
.build();
employeeRepository.save(employee);
employeeRepository.save(employee1);
// when - action or the behaviour that we are going test
List<Employee> employeeList = employeeRepository.findAll();
// then - verify the output
assertThat(employeeList).isNotNull();
assertThat(employeeList.size()).isEqualTo(2);
verify(employeeRepository, times(2)).save(user);
verify(employeeRepository, times(1)).findAll();
}
}
1条答案
按热度按时间rdrgkggo1#
Verify不适用于此处的任何一种情况,因为您要显式调用要在测试中验证的方法。
verify的通常原因是检查被测方法中模拟依赖项上的方法是否用正确的参数调用
范例