1

如何模拟属性注入。

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

我在这里找不到类似的模拟属性注入。

4

1 回答 1

1

因为在大多数情况下不建议使用属性注入,所以需要更改方法以适应这种情况。

以下示例使用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();
}
于 2019-09-20T12:29:39.917 回答