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

时间:2019-09-18 19:20:08

标签: c# unit-testing nunit autofac automoq

如何模拟属性注入。

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

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

1 个答案:

答案 0 :(得分:1)

由于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();
}