我希望模拟在方法“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"
(我是否应该实现接口?)
我的TestCode:
//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());
答案 0 :(得分:4)
您正在手动新建ServerPath
与TestTest
紧密联系的实例。这使得嘲弄它变得更加困难。它应作为依赖项注入TestTest
我建议抽象依赖
public interface IFilePath {
string MapPath(string folder, string filepath);
}
public class ServerPath : IFilePath {
public virtual string MapPath(string folder, string filepath) {
Console.WriteLine("ServerPath");
return (System.Web.Hosting.HostingEnvironment.MapPath(folder + filepath));
}
}
并使其成为TestTest
public class TestTest {
private readonly IFilePath filePath;
public TestTest (IFilePath filePath) {
this.filePath = filePath;
}
public virtual string Test1() {
string path = filePath.MapPath("folder", "filepath");
return path;
}
}
现在你可以模拟它进行测试
//Arrange
var expected = "test25";
var FakeServerPath = A.Fake<IFilePath>();
A.CallTo(() => FakeServerPath.MapPath(A<string>.Ignored, A<string>.Ignored))
.Returns(expected);
var sut = new TestTest(FakeServerPath);
//Act
var actual = sut.Test1();
//Assert
Assert.AreEqual(expected, actual);
最后,您将确保在组合根中注册DI容器的抽象和实现。