我正在使用起订量和 AutoFixture。
给定以下接口:
public interface Int1
{
Int2 Int2 { get; }
}
public interface Int2
{
string Prop1 { get; }
string Prop2 { get; }
}
我正在执行这样的测试:
using AutoFixture;
using AutoFixture.AutoMoq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class TestClass
{
[TestMethod]
public void Test1()
{
var f = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
var obj = f.Create<Mock<Int1>>();
obj.Object.Int2.Prop1.Should().NotBeNullOrEmpty();
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
[TestMethod]
public void Test2()
{
var f = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
var obj = f.Create<Mock<Int1>>();
obj.Setup(q => q.Int2.Prop1).Returns("test");
obj.Object.Int2.Prop1.Should().Be("test");
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
}
第一个测试通过,第二个测试失败:Expected obj.Object.Int2.Prop2 not to be <null> or empty, but found <null>
. 似乎在它的依赖属性之一上使用 Setup 时Int2
会清除整个Int2
对象(将所有属性设置为默认值)。这是为什么?如何避免?
obj.Object
创建后看起来像这样:
但执行后Setup
它看起来像这样(Prop2
is null
):
有趣的是,当我Int2
在创建属性后访问它时,它工作正常。所以这个测试通过了(变量int2
不在任何地方使用):
[TestMethod]
public void Test2()
{
var f = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
var obj = f.Create<Mock<Int1>>();
var int2 = obj.Object.Int2;
obj.Setup(q => q.Int2.Prop1).Returns("test");
obj.Object.Int2.Prop1.Should().Be("test");
obj.Object.Int2.Prop2.Should().NotBeNullOrEmpty();
}
有任何想法吗?
这也是一个 .csproj 文件供参考:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.15.0" />
<PackageReference Include="AutoFixture.AutoMoq" Version="4.15.0" />
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.1" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
</ItemGroup>
</Project>