I have below class
public class EmployeeService{
private final EmployeeRepository employeeRepo;
private final Map<String, Employee> cache;
@Autowired
public EmployeeService(EmployeeRepository employeeRepo, Map<String, Employee> cache){
this.employeeRepo = employeeRepo;
this.cache = cache;
}
public void loadFromDB(){
//repo call
cache.put("123", {employee object})
}
}
I want to write a junit for this where I need to check that value is inserted into cache. I tried below but there is no value in cache.
@Mock
private EmployeeRepository employeeRepo;
@Mock
private Map<String, Employee> cache;
@InjectMocks
private EmployeeService employeeService;
@BeforeEach
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
employeeService = new EmployeeService(employeeRepo, cache);
}
@Test
public void shouldLoadDataFromDBtoCache(){
when(employeeRepo.findActiveEmployee()).thenReturn(buildDataFromDB());
EmployeeService.loadFromDB();
Assertions.assertFalse(cache.isEmpty());
//Assertions.assertTrue(cache.containsKey("1625"));
//Assertions.assertTrue(cache.containsKey("1525"));
//Assertions.assertFalse(cache.containsKey("1425"));
}
For cache.containsKey()
getting assertion error
when I check size of the cache map is zero.
Assertions.assertFalse(cache.isEmpty()); // this is success.
How can I test hashmap containsKey
as above.
CodePudding user response:
From what I can see the minimal change you would need is the following:
@Mock
private EmployeeRepository employeeRepo;
private Map<String, Employee> cache = new HashMap<>();
private EmployeeService employeeService = new EmployeeService(employeeRepo, cache);
@Test
public void shouldLoadDataFromDBtoCache(){
when(employeeRepo.findActiveEmployee()).thenReturn(buildDataFromDB());
employeeService.loadFromDB();
Assertions.assertFalse(cache.isEmpty());
//Assertions.assertTrue(cache.containsKey("1625"));
//Assertions.assertTrue(cache.containsKey("1525"));
//Assertions.assertFalse(cache.containsKey("1425"));
}