【问题标题】:Test class method that calls private method in C# using moq and Xunit使用 moq 和 Xunit 在 C# 中调用私有方法的测试类方法
【发布时间】:2016-01-04 17:35:07
【问题描述】:

我有以下遗留类,我想添加一些单元测试来使用 Xunit 和 Moq

我要测试的类的伪代码如下:-

public class Foo : IFoo
{

       public StatusResposne GetStatus(string jobId)
       {
                   .
                   .
             var response = GetRequest(doc, targeturl);
                   .
                   .
       }

        private XDocument GetRequest(XDocument doc, string url)
        {
        }
}

现在我想测试 GetStatus,但我需要模拟 GetRequest 方法。

谁能建议最简单的方法?

干杯

【问题讨论】:

    标签: unit-testing moq xunit


    【解决方案1】:

    单元测试应该是黑盒测试,否则您的测试将过于脆弱:每次更改实现细节时,您都需要修复所有中断的测试。

    当您将 Foo 视为黑盒时,只有 GetStatus 可见。有一个私有的GetRequest 方法这一事实是无关紧要的。明天可能会有其他人来并决定重构 GetStatus 实现,从而不再使用 GetRequest 方法 - 也许该方法将不再存在。

    您应该测试GetStatusinstead of attempting to test implementation details 的可观察行为

    我需要模拟 GetRequest 方法

    这是不可能的。你可以only mock interfaces and accessible virtual methods

    【讨论】:

      【解决方案2】:

      您可以访问源代码吗? 一种方法是使 GetRequest 受保护虚拟并在某些继承的类中覆盖它,并将此类用于单元测试。

      最好将此方法移至其他类并将其用作依赖项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-04
        • 2021-06-16
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多