【发布时间】:2017-08-25 23:30:25
【问题描述】:
我希望模拟在方法“A”中调用的“B”方法
这是一个例子
在下面的示例中,我希望 MapPath 在被调用时始终返回一些“文本”。
两者属于不同的类别
public class TestTest
{
public virtual string Test1()
{
ServerPath IFilePath = new ServerPath();
string path = IFilePath.MapPath("folder", "filepath");
return path;
}
}
public class ServerPath
{
public virtual string MapPath(string folder, string filepath)
{
Console.WriteLine("ServerPath");
return (System.Web.Hosting.HostingEnvironment.MapPath(folder + filepath));
}
}
我想以这样一种方式模拟,即当调用MapPath 时,它应该总是返回"test25"(我是否应该实现一个接口?)
我的测试代码:
//I am using FakeitEasy
TestTest TestClass = new TestTest();
var FakeServerPath = A.Fake<ServerPath>();
var FakeTestTest = A.Fake<TestTest>();
A.CallTo(() => FakeServerPath.MapPath(A<string>.Ignored, A<string>.Ignored)).Returns("test25");
//Should I call FakeTestTest.Test1() or TestClass.Test1() ?
Console.WriteLine(TestClass.Test1());
【问题讨论】:
-
您正在手动更新
ServerPath的实例,该实例与TestTest紧密耦合。这使得嘲笑它变得更加困难。它应该作为依赖注入到TestTest中 -
您正在测试方法中创建
new ServerPath(),不确定是否可以替换。尝试在您的测试方法中提供虚假实现,而不是public virtual string Test1(ServerPath IFilePath)和TestTest TestClass = new TestTest(FakeServerPath )
标签: c# unit-testing fakeiteasy