NSubstitute Mock 静态类和静态方法

问题描述 投票:0回答:2

我正在尝试模拟静态类中的静态方法。我已经读到你不能这样做,但我正在寻找一种方法来解决这个问题。

我无法修改代码,并且在不静态的情况下制作相同的函数不是一个选项,因为他们检查测试的代码覆盖率,而我需要至少 90%。
我已经尝试模拟它使用的变量,但它不起作用。

public static class MyClass
{
    public static response MyMethod(HttpSessionStateBase Session, 
        otherVariable, stringVariable)
    {
        //some code
    }
}

public ActionResult MyClassTested()
{
    var response = MyClass.MyMethod(Session);
    //more code
}

我的问题是这个方法位于一个控制器内部,该控制器声明一个带有响应的 var,并根据该变量重定向用户。

c# visual-studio-2017 mocking nsubstitute
2个回答
2
投票

对于这类问题可能有更好的解决方案......取决于你能摆脱什么。

我最近在编写一个静态实用程序类(本质上用于创建 Guid 格式的各种截断)后自己遇到了这个问题。在编写集成测试时,我意识到我需要控制从该实用程序类生成的随机 Id,以便我可以故意向 API 发出该 Id,然后对结果进行断言。

我当时采用的解决方案是提供静态类的实现,但从非静态类中调用该实现(包装静态方法调用),我可以将其注册并注入到 DI 容器中。这个非静态类将是主要的主力,但是在我需要从另一个静态方法调用这些方法的实例中,静态实现将可用(例如,我编写了很多集成设置代码作为 IWevApplicationFactory 的扩展,并使用静态实用程序创建数据库名称)。

在代码中,例如

// my static implementation - only use this within other static methods when necessary. Avoid as much as possible.
public static class StaticGuidUtilities 
{
    public static string CreateShortenedGuid([Range(1, 4)] int take)
    {
        var useNumParts = (take > 4) ? 4 : take;
        var ids = Guid.NewGuid().ToString().Split('-').Take(useNumParts).ToList();
        return string.Join('-', ids);
    }
}


// Register this abstraction in the DI container and use it as the default guid utility class
public interface IGuidUtilities
{
    string CreateShortenedGuid([Range(1, 4)] int take);
}

// Non-static implementation
public class GuidUtitlities : IGuidUtilities
{
    public string CreateShortenedGuid([Range(1, 4)] int take)
    {
        return StaticGuidUtilities.CreateShortenedGuid(take);
    }
}

----

// In the tests, I can use NSubstitute...
// (Doesn't coding to the abstraction make our lives so much easier?)
var guidUtility = Substitute.For<IGuidUtilities>();
var myTestId = "test-123";
guidUtility.CreateShortenedGuid(1).Returns(myTestId);

// Execute code and assert on 'myTestId' 
// This method will call the injected non-static utilty class and return the id
var result = subjectUndertest.MethodUnderTest();

// Shouldly syntax
result.Id.ShouldBe(myTestId);

1
投票

如果您无法修改代码,那么我认为无法使用 NSubstitute 等基于 DynamicProxy 的库来解决此问题。这些库使用继承来拦截类上的成员,这对于静态和非虚拟成员来说是不可能的。

我建议尝试Fakes。该页面上的示例之一涉及存根

DateTime.Now

可以模拟静态成员的其他替代方案包括 TypeMock 和 Telerik JustMock。

相关问题:https://stackoverflow.com/q/5864076/906

© www.soinside.com 2019 - 2024. All rights reserved.