我想用Pose nu-get包为静态方法写一个测试,但是我不能理解语法应该是什么样子。在GitHub页面上有一个模拟示例,但它只适用于带有一个参数的void方法:
Shim consoleShim = Shim.Replace(() => Console.WriteLine(Is.A<string>())).With(
delegate (string s) { Console.WriteLine("Hijacked: {0}", s); });但我需要模拟方法:static bool ImagesExistsInDirectory(string ruleId, out string advertise_path);它与示例不同,它有输出参数并返回布尔值。我认为它应该看起来像这样,但它有参数错误和不匹配的参数。
Shim shim = Shim.Replace<string>(
() => FileOps.ImagesExistsInDirectory(Pose.Is.A<string>(), out Pose.Is.A<string>())
).With<string, string>(
delegate (string a, string b) { StubForStaticImages(a, out b); });有人能解释一下它是怎么工作的吗?
发布于 2020-02-23 21:38:42
第一个问题是尝试在Is.A<string>()中使用out。
第二个原因是定义来处理调用的委托与预期的不匹配,因为在lambda中定义delegate不能有out。
我首先创建了一个与要模拟的主题相匹配的单独委托,从而解决了这个问题
delegate bool StubForStaticImages(string id, out string path);并在定义填充程序时使用它。剩下的只需遵循文档中的示例即可。
出于测试目的,我定义了一个假主题
class FileOps {
public static bool ImagesExistsInDirectory(string ruleId, out string advertise_path) {
advertise_path = "test";
return false;
}
}执行测试时,以下示例的行为与预期一致
[TestMethod]
public void Pose_Static_Shim_Demo_With_Out_Parameter() {
//Arrange
var path = Is.A<string>();
var expectedResult = true;
var expectedPath = "Hello World";
var expectedId = "id";
string actualId = null; ;
StubForStaticImages stub = new StubForStaticImages((string a, out string b) => {
b = expectedPath;
actualId = a;
return expectedResult;
});
Shim shim = Shim
.Replace(() => FileOps.ImagesExistsInDirectory(Is.A<string>(), out path))
.With(stub);
//Act
string actualPath = default(string);
bool actualResult = default(bool);
PoseContext.Isolate(() => {
actualResult = FileOps.ImagesExistsInDirectory(expectedId, out actualPath);
}, shim);
//Assert - using FluentAssertions
actualResult.Should().Be(expectedResult); //true
actualPath.Should().Be(expectedPath); //Hello World
actualId.Should().Be(expectedId); //id
}注以上仅演示了mocking框架本身的功能。对您的实际测试进行必要的更改。
https://stackoverflow.com/questions/60362230
复制相似问题