Recently I'm wondering whether to write in note or Qiita.
How to write when you always forget and always want to mock a part.
--Method you want to mock
@Slf4j
@Service
public class HighHolidayService {
//Holiday list organized on a monthly basis
Map<String, List<LocalDate>> highHolidayCache = new HashMap<>();
//Method to be tested
public List<LocalDate> getHolidayList(LocalDate targetDate) {
String key = String.format("%d%02d", targetDate.getYear(), targetDate.getMonthValue());
if (highHolidayCache.containsKey(key)) {
return highHolidayCache.get(key);
}
List<LocalDate> holidayList = selectRecords(targetDate);
highHolidayCache.put(key, holidayList);
return holidayList;
}
//I want to mock this method!!!!
List<LocalDate> selectRecords(LocalDate targetDate) {
return null;
}
}
--How to write a test
package jp.co.hogehoge.service;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doReturn;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.mock.mockito.SpyBean;
public class HighHolidayServiceTest {
@SpyBean //of springboot@How to write spy
HighHolidayService highHolidayService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void Get the target holiday list() {
List<LocalDate> returnHolidayList = new ArrayList<>();
returnHolidayList.add(LocalDate.of(2019, 07, 28));
returnHolidayList.add(LocalDate.of(2019, 07, 21));
returnHolidayList.add(LocalDate.of(2019, 07, 15));
returnHolidayList.add(LocalDate.of(2019, 07, 14));
returnHolidayList.add(LocalDate.of(2019, 07, 7));
// doReturn(Object to return).when(spy object).method()
//Forget this way of writing! !!
doReturn(returnHolidayList).when(highHolidayService).selectRecords(anyObject());
LocalDate date = LocalDate.of(2019, 7, 15);
List<LocalDate> holidayList = highHolidayService.getHolidayList(date);
holidayList.forEach(System.out::println);
}
}
It's okay to mock each class because I often do it, but I forget to mock a part of the test target because it only occasionally appears. .. Or rather, there are a lot of talks that it is better to classify (yes, but it's logic that doesn't need to be that much).
Recommended Posts