java 抽象类的Sping Boot 单元测试?,

whhtz7ly  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(224)

在我的Sping Boot 应用程序中,我有以下服务和方法:

客户服务:

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();
}

机场服务:

@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;
    }
}

我正在尝试为getFileName()getData()方法编写单元测试,但是我不知道如何编写测试,或者我应该为getFileName()方法编写测试。因为,我不能模拟服务,因为我需要调用,并且没有任何repos等,我的请求通过。
那么,如何为这两个方法编写单元测试呢?

abithluo

abithluo1#

第一个建议是,为从抽象类扩展而来的具体类编写测试用例。
您可以查看此链接了解如何模拟类并测试类的方法。
https://howtodoinjava.com/spring-boot2/testing/spring-boot-mockito-junit-example/
举个例子:

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", "howtodoinjava@gmail.com");
        EmployeeVO empTwo = new EmployeeVO(2, "Alex", "kolenchiski", "alexk@yahoo.com");
        EmployeeVO empThree = new EmployeeVO(3, "Steve", "Waugh", "swaugh@gmail.com");

        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();
    }
}

相关问题