Wally Hartshorn
Wally Hartshorn

Reputation: 915

Should unit tests be written for private methods in event-driven code?

I'm writing my first Windows Forms program, using C#. It consists of 3 classes, one for each form. Other than the constructors, all of the methods within each class are private.

In trying to figure out how to write unit tests for the methods, I've found several posts and articles saying that there shouldn't be unit tests for private methods, because a private method is an implementation, not a public behavior.

I think I understand that reasoning, but that appears to mean that NONE of my code will have unit tests written for it. Everything is event-driven, happening when a button is clicked, a value is entered in a field, or a timer ticks.

Is that correct? Should my code have no unit tests at all? (I apologize if this is a duplicate of another question. I looked, but couldn't find anything that addressed this issue.)

Upvotes: 2

Views: 563

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23200

Indeed private methods are private implementations of your application and they shouldn't be unit test for them. Most of the time they are going to be called internally by public methods. By testing public methods then you are testing those private methods.

Your private methods are event driven as you said which will be executed when a user clicked on a button etc... If you think that your event handlers contain a lot of logic that should be tested then I recommend to follow this steps:

  1. Mark all classes (Forms) that contain your event handlers with the internal modifier. With this modifier those classes are only accessible in the the same assembly at which they are defined.
  2. You need also to mark all your event handlers methods with the public modifier. Because the classes at step 1 are internal those methods are only visible to the assembly where they are defined then only in your Windows Forms project.
  3. Into the AssemblyInfo.cs file of your Windows Forms project add this attribute : [assembly: InternalsVisibleTo("MyTestAssemblyName")] where MyTestAssemblyName is the assembly name of your test project.
  4. By doing the step 3. all your internal classes hence event handlers are also visible to your test project. At this step and referencing your Windows Formsq project to your test project then you can unit test your event handlers as you will do with every method.

Upvotes: 3

Related Questions