Naigel
Naigel

Reputation: 9644

C# test private static method of public static class

I'm a little confused about how to perform these test. I know about the existence of PrivateObject to test private class and PrivateType to test private static class, but how can I test a private static method of a PUBLIC static class?

public static class Clients {
    // CUT
    private static List<string> GenerateAddresses(string AppPath) {
        // CUT
    }
}

In my unit test class I tried

PrivateType testClients = new PrivateType(Clients);

but I get the error

'Clients' is a type, which is not valid in the given context

The error is a bit confusing and google bring me to completly different problems. Am I using 'Clients' wrong with PrivateType? Or should I test in a different way given that Clients is public?

Upvotes: 1

Views: 5289

Answers (2)

bashrc
bashrc

Reputation: 4835

var testClients = new PrivateType(typeof(Clients));

PrivateType expects a Type object rather than the symbol name.

But I would rather suggest re-thinking your test strategy. Testing private methods is usually not required. If you find that you are not able to get a decent code coverage from the public methods you may be in need for some refactoring.

Upvotes: 1

James Thorpe
James Thorpe

Reputation: 32202

Or should I test in a different way given that Clients is public?

Yes: Clients is the unit you're testing. If it's not exposing GenerateAddresses publicly, it's not part of its surface API, and in theory is just there to support the internals of the class.

In unit testing, test the observable behaviour of the class - don't worry about how it goes about doing it internally.

Upvotes: 4

Related Questions