Issue
What I just want to ask is to learn how we can use "verify" in these 2 methods. I added its usage to each method but I'm not sure whether it is right. I cannot handle with this process.
How can I solve it out?
Which is the best way to define verify in JUnit test method.
Here is my code snippet shown below.
@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();
}
}
Solution
Verify is not appropriate in either case here as you are explicitly calling the methods you want to verify in your test.
Usual reason for verify would be to check if a method on a mock dependency in your method under test had been called with the correct arguments
Example
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);
}
}
Answered By - johnnyutts
Answer Checked By - Marilyn (JavaFixing Volunteer)