0

I am new to junit testing and I want to write unit tests. Actually the methods does not return anything. It take the a list of signals and write it to a csv file. I am not sure how to test methods with void return types.

Anyone can help me ?

public void createCSV ( final ArrayList< Signal > messages, File file )
{
    try
    {
        // Use FileWriter constructor that specifies open for appending
        csvOutput = new MyWriter( new FileWriter( file, false ), ',' );

        // Create Header for CSV
        csvOutput.writeRecord( "Message Source" );
        csvOutput.writeRecord( "Message Name" );
        csvOutput.writeRecord( "Component" );
        csvOutput.writeRecord( "Occurance" );
        csvOutput.writeRecord( "Message Payload with Header" );
        csvOutput.writeRecord( "Bandwidth(with Header %)" );
        csvOutput.writeRecord( "Message Payload" );
        csvOutput.writeRecord( "Bandwidth(%)" );
        csvOutput.endOfRecord();

        for ( Signal signal : messages )
        {
            csvOutput.writeRecord( signal.getSource() );
            csvOutput.writeRecord( signal.getName() );
            csvOutput.writeRecord( signal.getComponent() );
            csvOutput.writeRecord( Integer.toString( signal.getOccurance() ) );
            csvOutput.writeRecord( Integer.toString( signal
                .getSizewithHeader() ) );
            csvOutput.writeRecord( Float.toString( signal
                .getBandwidthWithHeader() ) );
            csvOutput.writeRecord( Integer.toString( signal.getSize() ) );
            csvOutput.writeRecord( Float.toString( signal.getBandwidth() ) );
            csvOutput.endOfRecord();
        }
    }
    catch ( IOException e )
    {
        logger.error( "Error in writing CSV file for messages", e );
    }
    finally
    {
        try
        {
            if ( csvOutput != null )
            {
                csvOutput.flush();
                csvOutput.close();
            }
            messages.clear();
        }
        catch ( IOException ex )
        {
            ex.printStackTrace();
        }
    }
 }
}
Wearybands
  • 2,438
  • 8
  • 34
  • 53
  • Possible duplicate of http://stackoverflow.com/questions/3381801/how-do-i-unit-test-saving-file-to-the-disk – Raedwald Jul 05 '14 at 13:39

2 Answers2

3

One takes a map and sort it.

Pass in a map with known, unsorted values. Verify the map has been sorted after the method was called.

The other take the sorted map and write it to a csv file. I am not sure how to test methods with void return types.

Two options:

  1. Pass in a temporary file path, e.g. see JUnit temporary folders, then read that file after the method has been called and test it for correctness.

  2. Adjust your method to accept an OutputStream instead of a File. Then you can pass a ByteArrayOutputStream and verify its contents by calling toByteArray() and inspecting the bytes.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • Ok I created a map with unsorted values and I call the method passing that map how can I verify that the map is now sorted as the method does not return a sorted map – Wearybands Jun 30 '14 at 09:46
  • @UmairIqbal Either hand-craft a sorted map and compare the two or use an existing sort method that you trust (e.g. from JDK) to also sort the map and compare. – Duncan Jones Jun 30 '14 at 09:48
  • My question is I have two maps exactly with same content one is sorted and the other is unsorted I pass the unsorted map to the method which sorts the map. How can I compare both of them ? Do I need any assert statements? How? – Wearybands Jun 30 '14 at 09:50
  • @UmairIqbal What is the type of your map - `TreeMap`? – Duncan Jones Jun 30 '14 at 09:53
  • No it is simple Hashmap private HashMap< String, Signal > _SignalsMap = new HashMap< String, Signal >(); – Wearybands Jun 30 '14 at 09:54
  • @UmairIqbal A `HashMap` is not an ordered map,s o you can't sort it. You need a `TreeMap` to allow for sorting of keys. – Duncan Jones Jun 30 '14 at 09:56
  • I am using a SignalComparator Class which implements Comparator interface to sort my map based on the bandwidth value of each signal in the map – Wearybands Jun 30 '14 at 09:58
  • @UmairIqbal **You cannot sort a hash map**. If you have a `TreeMap` (or some other `SortedMap`), you can sort it by value (e.g. see [How to sort a Map on the values in Java?](http://stackoverflow.com/a/2581754/474189)). – Duncan Jones Jun 30 '14 at 09:59
  • Why not I am doing it. I have a Hashmap ok, where the key is String and value is a signal Object. Initially the map is filled with values and then I pass this map to sort the entries according to the maximum bandwidth value of the signals... Signals with max bandwidth comes first and signals with min bandwidth comes last. – Wearybands Jun 30 '14 at 10:02
  • @UmairIqbal Oh, I've just looked properly at your code. So you are not sorting a map - you are taking the values from a map, sorting them into a list then outputting them to file. Very different. So your code will work fine, just ensure your test does the same sorting then verify the output looks correct. – Duncan Jones Jun 30 '14 at 10:04
  • How can I verify in JUnit testing that the list is sorted... this is my question – Wearybands Jun 30 '14 at 10:06
  • @UmairIqbal I think I've explained that already. In your test, you will also need to sort the list. Then compare the result your method produces with your own sorted list. Just use `assertEquals(yourSortedList, theListFromTheMethod);`. – Duncan Jones Jun 30 '14 at 10:07
  • The only thing I am confused about is How can I get theListFromTheMethod as the method does not return anything – Wearybands Jun 30 '14 at 10:08
  • @UmairIqbal Based on your current design, you'll need to read in the contents of the file produced and reconstruct the list. Probably better that you refactor your code and have a separate method that just sorts the map values. Then you can test it in isolation. – Duncan Jones Jun 30 '14 at 10:09
1

Unit test for File

If you dont want to change the src code:

In the unit test I would pass a file to a temp path, call that create csv method and then open the file and dependendent of how many effort you want to invest:

check
1) if the file exists (use a filename genereated that contains the current time)
2) check that the length is more than 0 bytes
3) read the first and last line and check for expected content

But in most cases, an OutputStream is more flexible than a File parameter.
In productive code you pass a FileOutputStream, in your unit test a ByteArrayOutputStream, which you can parse using an ByteArrayInputStream.

This is the cleaner solution, since it does not create files which should be cleaned up, and it runs faster.

Unit test for sorting Just create an unsorted map. call you sort, and check the result to be sorted: Iterate and check that each next element is e.g greater than the previous one (or smaller depending on the sort order)

Just

AlexWien
  • 28,470
  • 6
  • 53
  • 83