Blog about software - ordep.dev 10月02日
测试私有方法
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

在单元测试中,通常建议只测试公共方法,但有时需要测试私有方法。通过反射,可以调用私有静态方法,确保其功能正确。虽然可以测试私有方法,但更好的做法是重构代码,将逻辑提取到可测试的公共方法中,保持代码清晰和可维护性。

🔍 通过反射,可以调用私有静态方法,确保其功能正确。这在需要验证底层逻辑时非常有用,但应谨慎使用。

🛠️ 虽然可以测试私有方法,但更好的做法是重构代码,将逻辑提取到可测试的公共方法中,保持代码清晰和可维护性。

🔧 测试私有方法可能导致测试与实现细节耦合,增加维护难度。建议优先考虑公共接口的测试,并通过辅助方法间接验证私有逻辑。

In a normal situation your public methods consume the private ones and when you’re testing,if you’re testing, you only test the public methods.

In Unit Testing, this assumption is totally right. You’re testing a Unit, and if you think Unit as a classthen you will only test the public methods.

The question is: how can we break a public method and test only the tiny bits?

In this case we have a User class with a private method that gives a Location based on an IpAddress.

public class User{    private static string GetUserCountry(string ipAddress)    {        return LookupService.GetLocation(ipAddress);    }}

We can test this GetUserCountry using Reflection.

As GetUserCountry is a static method we’ll be using PrivateTypeinstead of PrivateObject to instantiate the User class.

To invoke the GetUserCountry we can use PrivateType.InvokeStatic instead of PrivateObject.Invoke.

[TestMethod]public void IpAddressLocationMustMatchWithGetUserCountry(){        var obj = new PrivateType(typeof(User));    var method = "GetUserCountry";    var connection = new MockConnection() {         IpAddress = "92.250.0.0",         Country = "Portugal"    };    var expected = (string)obj.InvokeStatic(method,         new object[]         {             connection.IpAddress         }    );        Assert.AreEqual(expected, connection.Country);}

Now that we can test private methods but this solution makes sense?

Is there anything wrong about testing private methods? I don’t think so.

Should you break the things up and create another class with testable public methods? Yes, you should.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

单元测试 反射 私有方法 代码重构 测试策略
相关文章