C# 最低起订量+;Autofixture:使用从属特性的设置清除整个模拟对象
我正在使用Moq和AutoFixture 给定以下接口:C# 最低起订量+;Autofixture:使用从属特性的设置清除整个模拟对象,c#,unit-testing,moq,autofixture,automoq,C#,Unit Testing,Moq,Autofixture,Automoq,我正在使用Moq和AutoFixture 给定以下接口: 公共接口Int1 { Int2 Int2{get;} } 公共接口Int2 { 字符串Prop1{get;} 字符串Prop2{get;} } 我正在执行以下测试: 使用AutoFixture; 使用AutoFixture.AutoMoq; 使用FluentAssertions; 使用Microsoft.VisualStudio.TestTools.UnitTesting; 使用最小起订量; [测试类] 公共类TestClass { [
公共接口Int1
{
Int2 Int2{get;}
}
公共接口Int2
{
字符串Prop1{get;}
字符串Prop2{get;}
}
我正在执行以下测试:
使用AutoFixture;
使用AutoFixture.AutoMoq;
使用FluentAssertions;
使用Microsoft.VisualStudio.TestTools.UnitTesting;
使用最小起订量;
[测试类]
公共类TestClass
{
[测试方法]
公共void Test1()
{
var f=new Fixture().Customize(新的AutoMoqCustomization{ConfigureMembers=true});
var obj=f.Create();
obj.Object.Int2.Prop1.Should().NotBeNullOrEmpty();
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
[测试方法]
公共无效测试2()
{
var f=new Fixture().Customize(新的AutoMoqCustomization{ConfigureMembers=true});
var obj=f.Create();
obj.Setup(q=>q.Int2.Prop1).返回(“测试”);
obj.Object.Int2.Prop1.Should().Be(“测试”);
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
}
第一个测试通过,而第二个测试失败:预期obj.Object.Int2.Prop2不为空,但已找到
。似乎在Int2
的一个依赖属性上使用设置时,它会清除整个Int2
对象(将所有属性设置为默认值)。为什么呢?如何避免呢
obj.Object
创建后如下所示:
但是在执行Setup
之后,它看起来像这样(Prop2
是null
):
有趣的是,当我在创建Int2
属性后访问它时,它工作得很好。因此,该测试通过(变量int2
未在任何地方使用):
[TestMethod]
公共无效测试2()
{
var f=new Fixture().Customize(新的AutoMoqCustomization{ConfigureMembers=true});
var obj=f.Create();
var int2=obj.Object.int2;
obj.Setup(q=>q.Int2.Prop1).返回(“测试”);
obj.Object.Int2.Prop1.Should().Be(“测试”);
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
有什么想法吗
这也是一个.csproj文件供参考:
net5.0
简单地说,在设置Prop1
属性的返回值后,Int2
属性将得到一个不同的模拟实例。为了满足您的请求,Moq将生成一个新的mock,该mock将返回Prop1
的预期值
您可以将其视为等同于以下测试:
[事实]
公共无效测试3()
{
var obj2=new Mock();
Setup(x=>x.Property1).返回(Guid.NewGuid().ToString());
Setup(x=>x.Property2).返回(Guid.NewGuid().ToString());
var obj=新的Mock();
Setup(x=>x.PropertyB).Returns(obj2.Object);
对象设置(q=>q.PropertyB.Property1).返回(“测试”);
Assert.Equal(“test”,obj.Object.PropertyB.Property1);
Assert.NotEmpty(obj.Object.PropertyB.Property2);
}
如果您想保留初始的mock实例,只需更改Prop1
,那么可以使用mock.Get(T)
[事实]
公共无效测试4()
{
var f=new Fixture().Customize(新的AutoMoqCustomization{ConfigureMembers=true});
var obj=f.Create();
var obj2=Mock.Get(obj.Object.PropertyB);
obj2.Setup(q=>q.Property1).返回(“测试”);
Assert.Equal(“test”,obj.Object.PropertyB.Property1);
Assert.NotEmpty(obj.Object.PropertyB.Property2);
}
但我建议使用AutoFixture的冻结功能
[TestMethod]
公共无效测试5()
{
var fixture=新fixture()
.Customize(新的自动moqcustomization{ConfigureMembers=true});
var int2Mock=fixture.Freeze();
var int1Mock=fixture.Create();
int2Mock.Setup(q=>q.Prop1).Returns(“test”);
int1Mock.Object.Int2.Prop1.Should().Be(“测试”);
int1Mock.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}