AutoFixture / AutoMoq + NUnit AutoData冻结对象不由AutoMoq接口方法返回

时间:2014-08-08 16:02:30

标签: nunit autofixture automoq

使用AutoMoqCustomization我希望我的测试能够正常运行,但它失败了。

这是测试:

[Test, AutoMoqData]
public void Test1(
    [Frozen] MyObject myObject, 
    [Frozen] Mock<IRepo> stubMock, 
    MyClass sut, 
    int objectId)
{
    myObject.Id = objectId;
    MyObject result = sut.GetById(objectId);
    Assert.That(result.Id, Is.EqualTo(myObject.Id));
}

如果我添加一行代码,我可以使用它。但我不想这样做,因为它应该被推断?

    stubMock.Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => myObject);

MyClass有一个带有IRepo的构造函数。这就像一个魅力,因为如果我在我的测试中使用上面的行我有一个通过测试。

通常我在没有自动数据的情况下编写我的测试它更详细:

[Test]
public void Test3()
{
    IFixture fixture = new Fixture();
    int objectId = fixture.Create<int>();
    var stubMock = fixture.Freeze<Mock<IRepo>>();

    stubMock.Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => fixture.Create<MyObject>());
    fixture.Freeze<MyObject>(customise => customise.With(d => d.Id, objectId));

    var sut = new MyClass(stubMock.Object);
    MyObject result = sut.GetById(objectId);
    Assert.That(result.Id, Is.EqualTo(objectId));
}

所以我的代码已经非常清晰,但是就像最后一个樱桃一样...我想任何想法???

如何运行:

添加Nuget包:

<packages>
  <package id="AutoFixture" version="3.19.2" targetFramework="net45" />
  <package id="AutoFixture.AutoMoq" version="3.19.2" targetFramework="net45" />
  <package id="AutoFixture.NUnit2" version="3.19.2" targetFramework="net45" />
  <package id="Moq" version="3.1.416.3" targetFramework="net45" />
  <package id="NUnit" version="2.6.3" targetFramework="net45" />
</packages>

完整代码:

public class AutoMoqDataAttribute : AutoDataAttribute
    {
        public AutoMoqDataAttribute()
            : base(new Fixture().Customize(new AutoMoqCustomization()))
        {
        }
    }

    [TestFixture]
    public class Class1
    {
        public interface IRepo
        {
            MyObject GetObject(int id);
        }

        public class MyObject
        {
            public int Id { get; set; }
        }

        public class MyClass
        {
            private readonly IRepo _test;

            public MyClass(IRepo test) { _test = test; }

            public MyObject GetById(int id) { return _test.GetObject(id); }
        }

        [Test, AutoMoqData]
        public void Test1(
            [Frozen] MyObject myObject, [Frozen] IRepo stubMock, MyClass sut, int objectId)
        {
            myObject.Id = objectId;

            // expecting this commented line to be automatic because of the Frozen attribute on myObject? 
            // Mock.Get(stubMock).Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => myObject);

            MyObject result = sut.GetById(objectId);

            Assert.That(result.Id, Is.EqualTo(myObject.Id));
        }

        [Test, AutoMoqData]
        public void Test2(
            [Frozen] MyObject myObject, [Frozen] Mock<IRepo> stubMock, MyClass sut, int objectId)
        {
            myObject.Id = objectId;

            // expecting this commented line to be automatic because of the Frozen attribute on myObject? 
            // stubMock.Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => myObject);

            MyObject result = sut.GetById(objectId);

            Assert.That(result.Id, Is.EqualTo(myObject.Id));
        }

        [Test]
        public void Test3()
        {
            IFixture fixture = new Fixture();
            int objectId = fixture.Create<int>();
            var stubMock = fixture.Freeze<Mock<IRepo>>();

            stubMock.Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => fixture.Create<MyObject>());
            fixture.Freeze<MyObject>(customise => customise.With(d => d.Id, objectId));

            var sut = new MyClass(stubMock.Object);
            MyObject result = sut.GetById(objectId);
            Assert.That(result.Id, Is.EqualTo(objectId));
        }

    }

2 个答案:

答案 0 :(得分:3)

从3.20.0开始,您可以使用AutoConfiguredMoqCustomization。这将自动配置所有模拟,以便其成员&#39;返回值由AutoFixture生成。

虚拟方法/属性/索引器将设置为使用AutoFixture延迟生成其返回值。如果该方法具有out个参数,那么也会设置这些参数。

公共字段和密封属性将急切设置其值。

此测试现在应该通过:

[Test, AutoMoqData]
public void Test1(
    [Frozen] MyObject myObject,
    MyClass sut,
    int objectId)
{
    myObject.Id = objectId;
    MyObject result = sut.GetById(objectId);
    Assert.That(result.Id, Is.EqualTo(myObject.Id));
}

答案 1 :(得分:0)

感谢@MarkSeemann的一些提示,我正在解决这个'问题'。

我的想法

我开始使用AutoFixture.AutoMoq nuget包中的MockRelay类。我创建了一个重载MockRelayExtras,并将其添加到AutoMoqCustomozation。

这将反映在界面或抽象类上并相应地设置模拟

离。

Mock.Get(TInterface.Instance)
    .Setup( i => i.Method( It.IsAny<TParamType>() ) )
    .Returns( () => fixture.Create<TMethodResult>() );

现在这只适用于Interfaces和Abstract类(没有构造函数)

这是一个开始。代码将需要一些清理。此外,我希望其他人会喜欢,享受和使用它?

快乐的编码!

完整代码

这是一个有效基础测试的工作解决方案,证明它有效。

的app.config

(这修复了resharper en test runner)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Moq" publicKeyToken="69f491c39445e920" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.1408.717" newVersion="4.2.1408.717" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="nunit.core.interfaces" publicKeyToken="96d09a1eb7f44a77" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.3.13283" newVersion="2.6.2.12296" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

nuget包:

<packages>
  <package id="AutoFixture" version="3.19.2" targetFramework="net45" />
  <package id="AutoFixture.AutoMoq" version="3.19.2" targetFramework="net45" />
  <package id="AutoFixture.NUnit2" version="3.19.2" targetFramework="net45" />
  <package id="Moq" version="4.2.1408.0717" targetFramework="net45" />
  <package id="NUnit" version="2.6.3" targetFramework="net45" />
</packages>

属性

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(new Fixture().Customize(new AutoMoqCustomization(new MockRelayExtras())))
    {

    }
}

更新了MockRelay类

public class MockRelayExtras : MockRelay, ISpecimenBuilder
{
    public new object Create(object request, ISpecimenContext context)
    {
        object result = base.Create(request, context);

        var requestType = request as Type;
        if (requestType != null && result != null)
        {
            SetupMockWithInterface(requestType, result, context);
        }

        return result;
    }

    public static void SetupMockWithInterface(Type requestType, object result, ISpecimenContext context)
    {
        typeof (MockRelayExtras).GetMethod("SetupMockWithInterfaceGeneric")
            .MakeGenericMethod(requestType).Invoke(null, new[] {result, context});
    }

    public static void SetupMockWithInterfaceGeneric<TType>(TType result, ISpecimenContext context)
        where TType : class
    {
        //Mock.Get(stubMock).Setup(r => r.GetObject(It.IsAny<int>())).Returns(() => myObject);
        Mock<TType> genericMock = Mock.Get(result);

        foreach (MethodInfo methodInfo in typeof (TType).GetMethods())
        {
            // ISetup<TType,TMethodResult> setup = genericMock.Setup<TType,TMethodResult>( methodInfo )
            object setup =
                typeof (MockRelayExtras).GetMethod("SetupAsGenericFunc")
                    .MakeGenericMethod(typeof (TType), methodInfo.ReturnType)
                    .Invoke(null, new object[] {methodInfo, genericMock});

            // setup.Returns( () => context.Create<TResult>() )
            typeof (MockRelayExtras).GetMethod("SetupReturnsAsGenericFunc")
                .MakeGenericMethod(typeof (TType), methodInfo.ReturnType)
                .Invoke(null, new[] {setup, context});
        }
    }

    public static ISetup<TMock, TResult> SetupAsGenericFunc<TMock, TResult>(MethodInfo method, Mock<TMock> mock)
        where TMock : class
    {
        ParameterExpression input = Expression.Parameter(typeof (TMock));

        ParameterInfo[] parameters = method.GetParameters();

        Expression<Func<TMock, TResult>> setup = null;

        if (parameters.Length > 0)
        {
            IEnumerable<MethodCallExpression> properties =
                parameters.Select(
                    pi => Expression.Call(typeof (It), "IsAny", new[] {pi.ParameterType}, new Expression[0]));
            setup = Expression.Lambda<Func<TMock, TResult>>(
                Expression.Call(input, method, properties), input);
        }
        else
        {
            setup = Expression.Lambda<Func<TMock, TResult>>(
                Expression.Call(input, method), input);
        }


        return mock.Setup(setup);
    }

    public static void SetupReturnsAsGenericFunc<TMock, TResult>(ISetup<TMock, TResult> setup,
        ISpecimenContext context)
        where TMock : class
    {
        setup.Returns(() => context.Create<TResult>());
    }
}

测试

[TestFixture]
public class MockRelayExtrasTests
{
    public class RelayTestClass
    {
        public int Id { get; set; }
    }

    public class RandomInputData
        {
            public int Prop1 { get; set; }
            public string Prop2 { get; set; }
        }

    public interface ISingleResultNoInput
    {
        RelayTestClass SingleResultNoInput();
        IEnumerable<RelayTestClass> ListResultNoInput();
        RelayTestClass GetItemById(int id);
        RelayTestClass GetItemById(int id, string randomSearch);
        RelayTestClass GetItemBySearch(RandomInputData data);
    }

    [Test, AutoMoqData]
    public void Create_AutoMockInterfaceIEnumerableResults_InterfaceIsSetupWithIEnumerable(
        [Frozen] RelayTestClass itemTemplate,
        [Frozen] ISingleResultNoInput sut,
        [Frozen] IFixture fixture
        )
    {
        List<RelayTestClass> result = sut.ListResultNoInput().ToList();
        Assert.That(result[0], Is.EqualTo(itemTemplate));
    }

    [Test, AutoMoqData]
    public void Create_AutoMockInterfaceMethodsAutoMoqData_InterfaceIsSetup(
        [Frozen] RelayTestClass frozenItem, [Frozen] ISingleResultNoInput sut, int expectedId)
    {
        frozenItem.Id = expectedId;
        RelayTestClass result = sut.SingleResultNoInput();
        Assert.That(result.Id, Is.EqualTo(expectedId));
    }

    [Test, AutoMoqData]
    public void Create_AutoMockInterfaceMethodParameter_InterfaceIsSetup(
        [Frozen] RelayTestClass frozenItem, [Frozen] ISingleResultNoInput sut, int id)
    {
        frozenItem.Id = id;
        RelayTestClass result = sut.GetItemById(id);
        Assert.That(result.Id, Is.EqualTo(id));
    }

    [Test, AutoMoqData]
    public void Create_AutoMockInterfaceMethodsAutoMoqDataMultipleInput_InterfaceIsSetup(
        [Frozen] RelayTestClass frozenItem, [Frozen] ISingleResultNoInput sut, int id, string searchString)
    {
        frozenItem.Id = id;
        RelayTestClass result = sut.GetItemById(id, searchString);
        Assert.That(result.Id, Is.EqualTo(id));
    }

    [Test, AutoMoqData]
    public void Create_AutoMockInterfaceMethodsAutoMoqDataComplexInput_InterfaceIsSetup(
        [Frozen] RelayTestClass frozenItem, [Frozen] ISingleResultNoInput sut, RandomInputData input)
    {
        frozenItem.Id = input.Prop1;
        RelayTestClass result = sut.GetItemBySearch(input);
        Assert.That(result.Id, Is.EqualTo(input.Prop1));
    }
}

按包

自动生成插件
[NUnitAddin]
public class LocalAddin : Addin
{
}