[英]How to Verify object Type parameters in Moq
I want to test method execution with anonymous parameter, but with known properties. 我想用匿名参数来测试方法执行,但是要知道属性。
public interface IToTest
{
void MethodToTest(object data);
}
This is how I try to achieve this: 这就是我尝试实现的方法:
Mocker.Mock<IToTest>
.Verify(x=>x.MethodToTest(
It.Is<object>(
obj=>obj.Equals(new { DataProperty = "Test"})
)),
Times.Once());
Test is not passing. 测试未通过。
I don't want to use 我不想用
It.IsAny<object>()
because I know expected data. 因为我知道预期的数据。
Your current delegate is testing that the whole object obj
is equal to the anonymous type object new { DataProperty = "Test"}
- which is unlikely to be testing what you want. 您当前的委托正在测试整个对象
obj
等于匿名类型对象new { DataProperty = "Test"}
-这不太可能在测试您想要的对象。
What you need to do is check that: 您需要做的是检查:
1) obj
has a property with the name you are expecting. 1)
obj
具有您期望的名称的属性。
2) that property has a value that you are expecting. 2)该属性具有您期望的值。
Using reflection you can do both checks with something like the following: 使用反射,您可以使用以下内容进行两项检查:
Mocker.Mock<IToTest>
.Verify(x => x.MethodToTest(
It.Is<object>(
obj =>
obj.GetType().GetProperty("PropertyOne") != null &&
obj.GetType().GetProperty("PropertyOne").GetValue(obj).ToString() == "Test"
)),
Times.Once());
Important note - dont forget the NULL check on result of GetProperty()
for cases where the property does not exist. 重要说明 -如果属性不存在, 请不要忘记对
GetProperty()
结果进行NULL检查。
You will need to use reflection within the delegate to make your comparisons, or use something like FluentAssertions
to offload the heavy lifting 您将需要在委托中使用反射进行比较,或使用
FluentAssertions
类的FluentAssertions
来减轻繁重的工作
for example 例如
//...
var expected = new {
DataProperty = "Test"
//...known properties
};
Func<object, bool> match = _ => {
_.Should().BeEquivalentTo(expected);
return true;
};
Mocker.Mock<IToTest>
.Verify(x =>
x.MethodToTest(It.Is<object>(obj => match(obj))),
Times.Once());
Alternatively, you could have instead capture the object parameter in a callback and just assert the captured argument with fluent assertions. 或者,您可以改为在回调中捕获对象参数,然后仅使用流畅的断言来断言所捕获的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.