抽象类的 Spring Boot 单元测试?

问题描述 投票:0回答:1

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

Csv服务:

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()
方法编写测试。因为,我无法模拟该服务,因为我需要调用并且没有任何存储库等来传递我的请求。

那么,您将如何为这两种方法编写单元测试?

java spring spring-boot unit-testing testing
1个回答
1
投票

第一个建议是,为从抽象类扩展的具体类编写测试用例。

您可以查看此链接,了解如何模拟您的类并测试它的方法。

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.openMocks(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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.