1

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.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
dsi
  • 3,199
  • 12
  • 59
  • 102

1 Answers1

1

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();
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472