Testing writing into a csv file using JUnit

<>

This question is an exact duplicate of:

Answers


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.


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


Need Your Help

Automating a long SSH session

c# windows linux ssh

I'm looking for a way to create a c# program where I can script multiple session logins etc. I have to check about 200 servers for differences in a particular file, and I'd like to automate that w...

Ninject OnePerRequestBehaviour doesn't seem to work correctly?

c# inversion-of-control ninject

I've been using Ninject as my IOC in my web app. It's great and I think it works really well, however I have been trying to register some interfaces / classes as OnePerRequestBehaviour but it doesn't

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.