0

Moq と 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();
    }
}

最初のテストは成功しますが、2 番目のテストは失敗します: Expected obj.Object.Int2.Prop2 not to be <null> or empty, but found <null>. 依存プロパティの 1 つで Setup を使用すると、オブジェクトInt2全体がクリアされるInt2(すべてのプロパティがデフォルト値に設定される) ようです。何故ですか?それを避ける方法は?

obj.Object作成後は次のようになります。

セットアップの前に

しかし、実行後Setupは次のようになります ( Prop2is 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>
4

1 に答える 1