如何使用 AutoMock 模拟 属性 注入依赖

How to mock property injection dependency using AutoMock

如何模拟 属性 注入。

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

我在此处找不到与模拟 属性 注入类似的内容。

因为 property injection is not recommended in the majority of cases,需要更改方法以适应这种情况

以下示例使用 PropertiesAutowired() 修饰符注册主题以注入属性:

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);
        }
    }
}

此示例中使用的定义...

public class SystemUnderTest {
    public SystemUnderTest() {
    }

    public IDependency Dependency { get; set; }


    public string DoWork() {
        return this.Dependency.GetValue();
    }
}

public interface IDependency {
    string GetValue();
}