AutoFixture: mock methods don't return a frozen instance

前端 未结 2 418
孤街浪徒
孤街浪徒 2021-01-05 17:23

I\'m trying to write this simple test:

var fixture = new Fixture().Customize(new AutoMoqCustomization());

var pos         


        
2条回答
  •  萌比男神i
    2021-01-05 17:43

    You need to Freeze the IPostProcessingActionReader component.

    The following test will pass:

    [Fact]
    public void Test()
    {
        var fixture = new Fixture()
            .Customize(new AutoMoqCustomization());
    
        var postProcessingActionMock = new Mock();
    
        var postProcessingActionReaderMock = fixture
            .Freeze>();
    
        postProcessingActionReaderMock
            .Setup(x => x.CreatePostProcessingActionFromJobResultXml(
                It.IsAny()))
            .Returns(postProcessingActionMock.Object);
    
        var postProcessor = fixture.CreateAnonymous();
        postProcessor.Process("", "");
    
        postProcessingActionMock.Verify(action => action.Do());
    }
    

    Assuming that the types are defined as:

    public interface IPostProcessingAction
    {
        void Do();
    }
    
    public class PostProcessor
    {
        private readonly IPostProcessingActionReader actionReader;
    
        public PostProcessor(IPostProcessingActionReader actionReader)
        {
            if (actionReader == null)
                throw new ArgumentNullException("actionReader");
    
            this.actionReader = actionReader;
        }
    
        public void Process(string resultFilePath, string jobId)
        {
            IPostProcessingAction postProcessingAction = this.actionReader
                .CreatePostProcessingActionFromJobResultXml(resultFilePath);
    
            postProcessingAction.Do();
        }
    }
    
    public interface IPostProcessingActionReader
    {
        IPostProcessingAction CreatePostProcessingActionFromJobResultXml(
            string resultFilePath);
    }
    

    In case you use AutoFixture declaratively with the xUnit.net extension the test could be simplified even further:

    [Theory, AutoMoqData]
    public void Test(
        [Frozen]Mock readerMock,
        Mock postProcessingActionMock,
        PostProcessor postProcessor)
    {
        readerMock
            .Setup(x => x.CreatePostProcessingActionFromJobResultXml(
                It.IsAny()))
            .Returns(postProcessingActionMock.Object);
    
        postProcessor.Process("", "");
    
        postProcessingActionMock.Verify(action => action.Do());
    }
    

    The AutoMoqDataAttribute is defined as:

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

提交回复
热议问题