Search code examples
c#unit-testingnunitautofacautomoq

How to mock property injection dependency using AutoMock


How to mock a property injection.

using (var mock = AutoMock.GetLoose())
{
    // mock.Mock creates the mock for constructor injected property 
    // but not property injection (propertywiredup). 
}

I could not find similar here to mock property injection.


Solution

  • Because property injection is not recommended in the majority of cases, the approach will need to be changed to accommodate that case

    The following example registers the subject with the PropertiesAutowired() modifier to inject properties:

    using Autofac;
    using Autofac.Extras.Moq;
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    [TestClass]
    public class AutoMockTests {
        [TestMethod]
        public void Should_AutoMock_PropertyInjection() {
            using (var mock = AutoMock.GetLoose(builder => {
                builder.RegisterType<SystemUnderTest>().PropertiesAutowired();
            })) {
                // Arrange
                var expected = "expected value";
                mock.Mock<IDependency>().Setup(x => x.GetValue()).Returns(expected);
                var sut = mock.Create<SystemUnderTest>();
    
                sut.Dependency.Should().NotBeNull(); //property should be injected
    
                // Act
                var actual = sut.DoWork();
    
                // Assert - assert on the mock
                mock.Mock<IDependency>().Verify(x => x.GetValue());
                Assert.AreEqual(expected, actual);
            }
        }
    }
    

    Where definitions used in this example ...

    public class SystemUnderTest {
        public SystemUnderTest() {
        }
    
        public IDependency Dependency { get; set; }
    
    
        public string DoWork() {
            return this.Dependency.GetValue();
        }
    }
    
    public interface IDependency {
        string GetValue();
    }