In my Spring Boot app, I have the following services and methods:
CsvService:
public abstract class CsvService<T extends CsvBean> {
public List<T> readFromCsv(Class<T> type, CsvToBeanFilter filter) {
List<T> data = new ArrayList<>();
try {
Resource resource = new ClassPathResource(getFileName());
// code omitted
} catch (IOException ex) {
// code omitted
}
return data;
}
protected abstract String getFileName();
}
AirportService:
@Service
public class AirportService extends CsvService<AirportBean> {
@Override
protected String getFileName() {
return "airport.csv";
}
@Override
protected List<AirportBean> getData(CsvToBean<AirportBean> csvToBean) {
List<AirportBean> airports = new ArrayList<>();
// iterate through data
for (AirportBean bean : csvToBean) {
// code omitted
airports.add(airport);
}
return airports;
}
}
I am trying to write unit test for getFileName()
and getData()
methods, but I have no idea how to write test or should I write test especially for getFileName()
method. Because, I cannot mock the service as I need to call and there is not any repos, etc. where my request passing.
So, how would you write a Unit test for these 2 methods?
CodePudding user response:
First advice would be, write test cases for concrete class which extends from abstract class.
You can check this link for how you can mock your classes and test methods of it.
https://howtodoinjava.com/spring-boot2/testing/spring-boot-mockito-junit-example/
An example of it:
public class TestEmployeeManager {
@InjectMocks
EmployeeManager manager;
@Mock
EmployeeDao dao;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getAllEmployeesTest()
{
List<EmployeeVO> list = new ArrayList<EmployeeVO>();
EmployeeVO empOne = new EmployeeVO(1, "John", "John", "[email protected]");
EmployeeVO empTwo = new EmployeeVO(2, "Alex", "kolenchiski", "[email protected]");
EmployeeVO empThree = new EmployeeVO(3, "Steve", "Waugh", "[email protected]");
list.add(empOne);
list.add(empTwo);
list.add(empThree);
when(dao.getEmployeeList()).thenReturn(list);
//test
List<EmployeeVO> empList = manager.getEmployeeList();
assertEquals(3, empList.size());
verify(dao, times(1)).getEmployeeList();
}
}