0

I'm trying to write unit tests. The unit tests have input of a stringed csv file. So I'm having csvFileDataAsString as the simulated input.

String csvFileDataAsString = 'Column1,Column2,Column3\n00301,true,false\n00302,false,false'

The unit test is failing. With debug prints, I found: List<String> data = csvFileDataAsString.split('\n'); ---> data.size()= 1??? List<String> data = csvFileDataAsString.split('\\n'); ---> data.size()still = 1???

List<String> columndata = caseContactsData[0].split(','); --> columndata.size() = 7 ??

Seems like the split by new line was not done properly in my dummy test string. How should I define the test string properly please? And should I use split by \n or \\n please?

Thank you.

-------------------------Update with complete code ------

List<Object__c> readObjectCSVFile(String csvFileDataAsString) {
        List<Object__c> Objects = new List<Object__c>();
        List<String> ObjectsData = csvFileDataAsString.split('\n');
        // Also tried List<String> ObjectsData = csvFileDataAsString.split('\\n'); but size still gives as 1

        System.debug(ObjectsData.size()); ---> 1 (instead of excepted 3 lines)

        if (csvFileDataAsString.length() == 0 || ObjectsData.isEmpty()) {
            showError('readObjectCSVFile: CSV file is empty');
            return Objects;
        }

        List<String> columnNames = ObjectsData[0].split(',');
        System.debug(columnNames.size()); ---> 7 (instead of excepted 3 cells in a row)

        // more process logic based on cell data...
        }
        return Objects;
    }

input string was String csvFileDataAsString = 'Column1,Column2,Column3\n00301,true,false\n00302,false,false'

5
  • Could you include a complete code sample that reproduces this issue?
    – David Reed
    Dec 29, 2019 at 0:31
  • split('\\n') should work.
    – sfdcfox
    Dec 29, 2019 at 2:07
  • @DavidReed updated.thank you Dec 29, 2019 at 4:33
  • @sfdcfox tried with \\n in test-string, and also in function splitby, no luck. thank you. Dec 29, 2019 at 4:34
  • N.B. this parser will break if the csv has embedded line breaks or commas in a cell. You can find better parsers elsewhere on stackexchange or github
    – cropredy
    Dec 31, 2019 at 1:30

1 Answer 1

0

Post the unit test method too. As per the comments, both \n and \\n will work. Run the following test to verify this:

@IsTest
static void csvSplitWithNewline() {
    String csv = 'Column1,Column2,Column3\n00301,true,false\n00302,false,false';
    System.assertEquals(3, csv.split('\n').size());
    System.assertEquals(3, csv.split('\\n').size());
}

On the topic of parsing CSV strings, you may want to consider implementing a custom iterator to process your CSV if you are expecting a large number of rows. Here is an answered question about this.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .