jdiaz jdiaz -4 years ago 191
C# Question

Unit testing void methods?

What is the best way to unit test a method that doesn't return anything? Specifically in c#.

What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.

Answer Source

If a method doesn't return anything, it's either one of the following

  • imperative - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
  • informational - just notifying someone that something happened (without expecting action or response) respectively.

Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.

void DeductFromBalance( dAmount ) 

can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount

Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.

void OnAccountDebit( dAmount )  // emails account holder with info

can be tested by verifying if the email is being sent

Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.

string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );

String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like

InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download