Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d6bd9d1
commit ad4c3bf
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
57 changes: 57 additions & 0 deletions
57
...t/java/com/examples/spring/demo/services/EmployeeServiceWithMockBeanSpringBootTestIT.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package com.examples.spring.demo.services; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
import static org.junit.Assert.assertNull; | ||
import static org.mockito.BDDMockito.given; | ||
import static org.mockito.Mockito.verify; | ||
|
||
import java.util.Arrays; | ||
|
||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.test.context.SpringBootTest; | ||
import org.springframework.boot.test.mock.mockito.MockBean; | ||
import org.springframework.test.context.junit4.SpringRunner; | ||
|
||
import com.examples.spring.demo.model.Employee; | ||
import com.examples.spring.demo.repositories.EmployeeRepository; | ||
import com.examples.spring.demo.services.EmployeeService; | ||
|
||
/** | ||
* Uses Spring dependency injection, to inject (in the Spring sense) mocked | ||
* beans (that can then be stubbed with Mockito); {@link SpringBootTest} | ||
* loads the complete application context for dependency injection. | ||
* | ||
* Just a demonstration of {@link SpringBootTest}; it doesn't make much sense | ||
* to use it with mocking. | ||
*/ | ||
@RunWith(SpringRunner.class) | ||
@SpringBootTest | ||
public class EmployeeServiceWithMockBeanSpringBootTestIT { | ||
|
||
@MockBean | ||
private EmployeeRepository employeeRepository; | ||
|
||
@Autowired | ||
private EmployeeService employeeService; | ||
|
||
@Test | ||
public void test_getMaxSalariedEmployee_withNoEmployees() { | ||
assertNull(employeeService.getMaxSalariedEmployee()); | ||
verify(employeeRepository).findAll(); | ||
} | ||
|
||
@Test | ||
public void test_getMaxSalariedEmployee_withEmployees() { | ||
given(employeeRepository.findAll()). | ||
willReturn(Arrays.asList( | ||
new Employee(1, "first", 1000), | ||
new Employee(2, "second", 5000), | ||
new Employee(3, "third", 2000) | ||
)); | ||
assertThat(employeeService.getMaxSalariedEmployee().getName()). | ||
isEqualTo("second"); | ||
verify(employeeRepository).findAll(); | ||
} | ||
} |