简体   繁体   English

公共静态类的C#测试私有静态方法

[英]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? 我知道存在PrivateObject测试私有类的PrivateTypePrivateType测试私有静态类的PrivateObject的存在,但是我如何测试PUBLIC静态类的私有静态方法?

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. 该错误有点令人困惑,Google将我带到了完全不同的问题。 Am I using 'Clients' wrong with PrivateType ? 我在PrivateType使用“客户端”错误吗? Or should I test in a different way given that Clients is public? 还是鉴于Clients是公开的,我应该以其他方式进行测试吗?

Or should I test in a different way given that Clients is public? 还是鉴于Clients是公开的,我应该以其他方式进行测试吗?

Yes: Clients is the unit you're testing. 是: Clients是您要测试的单元。 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. 如果它不公开公开GenerateAddresses ,则它不是其表面​​API的一部分,并且从理论上讲,它只是在支持该类的内部。

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. PrivateType需要Type对象而不是符号名称。

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. 如果发现无法从公共方法中获得不错的代码覆盖率,则可能需要进行一些重构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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