zaq
zaq

Reputation: 2661

Unit testing and Test Driven Development of non public methods

I am new to the concept of TDD and am just starting to get the hang of writing good unit tests for the public interface of my applications.

Currently, I am working on a class library where the public interface is relatively small but there is a large amount of complexity that goes on in classes behind the scenes. This functionality is implemented in internally scoped classes and methods and are therefore not available for unit testing. I do not want to make these classes and methods public because they should not be available to the consuming application but I don't feel like I can adequately test all of the application's functionality without writing more specific test cases.

Can someone explain to me how I might accomplish such testing? Or is something wrong with my approach that I could change to facilitate better testing.

BTW, I am working in a C# .NET environment but I think my question could also apply to Java or any number of other platforms as well.

Upvotes: 3

Views: 195

Answers (4)

Adronius
Adronius

Reputation: 256

Do not unit test private methods. If it is worth testing, then it is worth to be public or functionality should be in own class. Seems like broken SOLID principles.

Upvotes: 0

Eiver
Eiver

Reputation: 2635

Most unit test gurus would tell you, that you should only test the public interface. However I do not agree with them, as I often ended up in a similar situation. If you are using C# and a version of Visual Studio, that supports unit testing, then you are lucky. Simply click Test-> New Test... and then select "Unit Test Wizard". Then select any methods, that you would like to test (including private methods). Visual Studio will automatically generate unit tests for you. For private methods it will create shadow classes named like MyClass_Accessor. These classes are exactly the same as your original classes, but their private members are public. These shadow classes also get automatically updated if you change your class.

Upvotes: 0

k3b
k3b

Reputation: 14755

Since you are using dotnet you can make the other classes dll-internal and use the internalsvisibleto attribute in the businessclass to allow the unittest-dll to access them.

Upvotes: 1

John Watts
John Watts

Reputation: 8885

In Java, you would typically either get around the access checks using something like PowerMock's Whitebox class or use default (package) scope. In other words, no access modifier at all. The unit tests are typically in the same package as the class under test. In .NET, you might be able to get similar functionality with internal scope, but it sounds like you would need your tests and your code under test to be in the same assembly in that case. If that is a problem, maybe you can make your test assembly a friend assembly of the code under test.

Upvotes: 0

Related Questions