简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM