c# - 我正在尝试用 C# 为静态方法编写单元测试

标签 c# unit-testing

我正在学习 C# Web 应用程序的单元测试。我陷入了上述场景。我不确定我是否以正确的方式这样做。我有用于单元测试的 FakePath 类。如何在 MSTest 中为静态方法 Abc.log() 编写单元测试?

public class Abc
{
    public static void log(string msg)
    {
        //Read on Write on path;
        string path = getPath(new ServerPath());
    }

    public static string getPath(IServerPath path)
    {
        return path.MapPath("file.txt");
    }
}

interface IServerPath()
{
    string MapPath(string file);
}

class ServerPath : IServerPath
{
    string MapPath(string file)
    {
        return HttpContext.Current.Server.MapPath(file);
    }
}

class FakeServerPath : IServerPath
{
    string MapPath(string file)
    {
        return @"C:\"+file;
    }
}

最佳答案

您正在尝试测试 void 方法,因此断言此方法的选项之一是验证该方法是否被调用:

string expectedStr = "c:\file.txt";
[TestMethod]
public void FakeServerPath_VerifyMapPathWasCalled()
{
    var fakeServerPath = Isolate.Fake.NextInstance<ServerPath>();
    Isolate.WhenCalled(() => fakeServerPath.MapPath("")).WillReturn(expectedStr);

    Abc.log("");

    Isolate.Verify.WasCalledWithExactArguments(() => fakeServerPath.MapPath("file.txt"));
}

另一种选择是通过修改 ServerPath 的返回值来测试 getPath(IServerPath path) 方法的返回值 MapPath(string file) 方法返回想要的值,并断言返回值是否符合预期。

string expectedStr = "c:\file.txt";
[TestMethod]
public void ModifyReturnValueFromMapPath_IsEqualToExpactedStr()
{
    var fakeServerPath = Isolate.Fake.NextInstance<ServerPath>();

    Isolate.WhenCalled(() => fakeServerPath.MapPath("")).WillReturn(expectedStr);

    var result = Abc.getPath(fakeServerPath);

    Assert.AreEqual(expectedStr, result);
}

请注意,通过使用 TypeMock Isolator您将能够伪造“ServerPath”的 future 实例,而无需更改原始代码。 如果需要,TypeMock 还可以模拟 HttpContext 类,如下所示:

string expectedStr = "c:\file.txt";
[TestMethod]
public void ModifyReturnValueFromHttpContext_IsEqualToExpactedStr()
{
    var serverPath = new ServerPath();

    Isolate.WhenCalled(() => HttpContext.Current.Server.MapPath("")).WillReturn(expectedStr);

    var result = Abc.getPath(serverPath);

    Assert.AreEqual(expectedStr, result);
}

关于c# - 我正在尝试用 C# 为静态方法编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193501/

相关文章:

c# - 如何清除 silverlight 中的日期选择器控件?

C#单元测试代码题

unit-testing - TDD 测试数据重复

unit-testing - .NET 核心使用 Xunit + Autofixture + Moq 编写更好的单元测试

c# - 使用 C# 从 SQL 显示和保存 "time"数据类型?

c# - 如何从程序集/WCF 服务内部访问程序集版本和名称?

c# - 使用 LINQ 在 C# 中的基于服务的数据库中搜索值是否存在

c# - 使用 JSON.NET 反序列化值为字段名称的 JSON

python - 在单元测试中卡住数据库时间(django 和 sqlite)

python - 检测到一个方法是递归的而不调用它?