jeudi 16 janvier 2020

How can I unit test this CSV parser that returns a ByteArrayDataSource?

I am trying to write a unit test for a CSV parser but I don't have any experience testing a ByteArrayDataSource. The parser takes a list and then writes it to a CSV file. Here is the parser:

@Component
    public class CsvBuilderUtil {

        String[] HEADERS = {"PROP_1", "PROP_2", "PROP_3", "PROP_4",  "PROP_5", "PROP_6", "PROP_7"};

        @Autowired
        EmailNotificationDao emailNotificationDao;

        @Autowired
        EmailService emailService;

        public InputStream createCSVFile (List<EmailNoticationData> emailNoticationDataList) throws IOException {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Writer writer = new OutputStreamWriter(stream);
            try (CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader(HEADERS))) {
                for (EmailNoticationData emailNoticationData : emailNoticationDataList) {
                    printer.printRecord(emailNoticationData.getProp1(),
                            emailNoticationData.getProp2(),
                            emailNoticationData.getProp3(),
                            emailNoticationData.getProp4(),
                            emailNoticationData.getProp5(),
                            emailNoticationData.getProp6(),
                            emailNoticationData.getProp7());
                }
            } catch (IOException e){
                throw e;
            }
            byte[] array =  stream.toByteArray();
            stream.flush();
            stream.close();
            InputStream result = new ByteArrayInputStream(array);

            return result;
        }
    }

My first thought was to mock the ByteArrayOutputStream to make an expected stream and then compare that with the actual CsvBuilderUtil.createCsvFile. But I have tried this over and over with no success. Any advice would be greatly appreciated. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire