我正在学习 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/