c# - 我应该将私有(private)方法提取到单元测试类吗?

标签 c# unit-testing testing

<分区>

我有以下类,其中我想要进行单元测试的所有逻辑都发生在我提取的私有(private)方法中,以供两个要调用的 Handle 方法重用。我坚持的是对这个类进行单元测试的正确方法。我想断言基本上有 4 种可观察到的行为:

  1. 当注册不存在时不调用“替换”
  2. 当文档不存在时不调用“替换”
  3. 当文档消息是最新的时不调用“替换”
  4. 当所有其他条件都满足时调用“替换”

我可以轻松地复制两个公共(public) Handle 方法的所有单元测试。但我想知道将私有(private)方法提取到使用我可以直接测试的公共(public)方法公开此行为的类是否更合适。

想法?

public class Denormalizer :
    INotificationHandler<LightsMessageReceived>,
    INotificationHandler<AnnouncementsMessageReceived>
{
    public Task Handle(AnnouncementsMessageReceived notification, CancellationToken cancellationToken)
    {
        return HandleMessage(notification, document => document.Announcements, cancellationToken);
    }

    public Task Handle(LightsMessageReceived notification, CancellationToken cancellationToken)
    {
        return HandleMessage(notification, document => document.Lights, cancellationToken);
    }

    private async Task HandleMessage(InventoryMessage message, Func<SaleRegistration, ISequenced> getMessageId, CancellationToken cancellationToken)
    {
        var registration = await docContext.CsoMessage.GetSaleRegistration(message.SiteId, message.InventoryId, cancellationToken);

        if (registration == null) return;

        var document = await docContext.SaleRegistration.Get(message.SiteId, message.InventoryId, 
            registration.Data.SaleDate, registration.Data.SaleType, cancellationToken);

        if (document == null) return;

        if (getMessageId(document).IsCurrent(message.MessageId)) return;

        document.Map(message);

        await docContext.SaleRegistration.Replace(document);
    }
}

最佳答案

最干净的方法是将代码移动到另一个您可以测试的类。但是,类和方法都不需要是public。您还可以使用 internal 访问修饰符标记它们,这样您就只能访问同一程序集中的代码。

此外,您明确授予内部成员访问权限的程序集也可以访问该方法。您可以使用 InternalsVisibleTo主程序集上的属性并授予对单元测试程序集的访问权限。这样,您就不会完全发布方法,同时允许单元测试访问它。

当然,如果您决定将方法保留在类中并仅将其标记为 internal,这也有效,因此您不必创建自己的类(尽管这可能是清洁工)。

关于c# - 我应该将私有(private)方法提取到单元测试类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807501/

相关文章:

c# - 从 WSE 3.0 客户端请求中删除 WS-Addressing/WS-Security 部分

C# 等待 TCP 响应的良好实践

python unittest导入类子目录

php - 对遗留 php 应用程序进行单元测试 — 如何防止意外的数据库调用

testing - 这个 fatal error 从何而来? cakephp phpunit

unit-testing - maven project junit test all fail 因为无法编译源代码

javascript - [React-Native][Jest]SyntaxError : Unexpected token import

c# - -Convert.ToSingle 是做什么的?

c# - 每个匹配生命周期范围的实例,默认?

python - 使用参数化测试或单独测试的测试工作流程