模拟接口在每个属性上获得两个幻像调用

时间:2016-12-21 17:32:19

标签: c# moq xunit autofixture automoq

我有一个简单的类,它将一条消息写入控制台,并以当前时间为前缀。它依赖于IDateTimeProvider接口作为DateTime.Now

的抽象
public interface IDateTimeProvider
{
    DateTime Now { get; }
    DateTime UtcNow { get; }
}

public class MessageWriter
{
    private readonly IDateTimeProvider _dateTimeProvider;

    public MessageWriter(IDateTimeProvider dateTimeProvider)
    {
        _dateTimeProvider = dateTimeProvider;
    }

    public void Write(string message)
    {
        Console.WriteLine($"{_dateTimeProvider.Now.ToShortTimeString()} : {message}");
    }
}

为了测试Write方法调用IDateTimeProvider.Now我使用xUnit,AutoFixture和Moq编写了以下测试:

public class MessageWriterTests
{
    [Theory, AutoMoqData]
    public void Write_Always_CallsDateTimeProvider(
        [Frozen] Mock<IDateTimeProvider> dateTimeProviderMock,
        MessageWriter sut,
        string message)
    {
        sut.Write(message);

        dateTimeProviderMock.Verify(m => m.Now, Times.Once());
    }
}

我正在使用http://blog.ploeh.dk/2010/10/08/AutoDataTheorieswithAutoFixture/

上显示的AutoMoqDataAttribute
public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(new Fixture()
            .Customize(new AutoMoqCustomization()))
    {
    }
}

上述测试失败,并显示以下消息:

  

模拟一次的预期调用,但是是3次:m =&gt; m.Now

     

未配置任何设置。

Performed invocations:
IDateTimeProvider.Now
IDateTimeProvider.UtcNow
IDateTimeProvider.Now
IDateTimeProvider.UtcNow
IDateTimeProvider.Now
   at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable`1 setups,  IEnumerable`1 actualCalls, Expression expression, Times times, Int32 callCount)
   at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
   at Moq.Mock.VerifyGet[T,TProperty](Mock`1 mock, Expression`1 expression, Times times, String failMessage)
   at Moq.Mock.Verify[T,TResult](Mock`1 mock, Expression`1 expression, Times times, String failMessage)
   at Moq.Mock`1.Verify[TResult](Expression`1 expression, Times times)
   at MoqBug.Tests.MessageWriterTests.Write_Always_CallsDateTimeProvider(Mock`1 dateTimeProviderMock, MessageWriter sut, String message) in c:\Users\rik van der sanden\documents\visual studio 2015\Projects\MoqBug\MoqBug.Tests\MessageWriterTests.cs:line 21

所以我的问题是:额外的调用(接口上的每个属性有两个)来自哪里?

如果我放弃使用AutoMoqDataAttribute问题就会消失:

    [Theory, AutoData]
    public void Write_Always_CallsDateTimeProvider(
        string message)
    {
        IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
        Mock<IDateTimeProvider> dateTimeProviderMock = fixture.Freeze<Mock<IDateTimeProvider>>();
        MessageWriter sut = fixture.Create<MessageWriter>();

        sut.Write(message);

        dateTimeProviderMock.Verify(m => m.Now, Times.Once());
    }

此版本的测试通过,但我宁愿使用参数。

1 个答案:

答案 0 :(得分:1)

原来我使用的是Moq版本4.1.1308.2120,这是AutoFixture.AutoMoq所需的最低版本,因此是Nuget安装的版本。

Moq更新到最新版本(在此特定情况下为4.5.28)修复了问题。