Sping Boot 存储库JUnit存储库测试-验证方法问题(无法工作)

uemypmqf  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(118)

我想问的是,这两种方法中如何使用“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();

    }

}
rdrgkggo

rdrgkggo1#

Verify不适用于此处的任何一种情况,因为您要显式调用要在测试中验证的方法。
verify的通常原因是检查被测方法中模拟依赖项上的方法是否用正确的参数调用
范例

public class Calculator {

    private Adder adder;

    public Calculator(Adder adder) {
        this.adder = adder;
    }

    public int addNumbers(int a, int b) {
        return adder.add(a, b);
    }
}

public class Adder {

    public int add(int a, int b) {
        return a + b;
    }
}

@ExtendWith(SpringExtension.class)
public class CalculatorTest {

    @InjectMocks
    private Calculator calculator;

    @Mock
    private Adder adder;

    @Test
    public void addOneAndThreeReturnsFour() {
        when(adder.add(1, 3)).thenReturn(4);

        assertEquals(4, calculator.addNumbers(1, 3));

        verify(adder).add(1, 3);
    }
}

相关问题