我正在学习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"));
}


另一种选择是通过修改getPath(IServerPath path) ServerPath's方法的返回值以返回所需值,并断言返回值是否符合预期来测试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”的将来实例,而无需更改原始代码。
并且,如有必要,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/

10-11 22:27
查看更多