【问题标题】:How to mock property injection dependency using AutoMock如何使用 AutoMock 模拟属性注入依赖项
【发布时间】:2019-09-18 19:20:08
【问题描述】:

如何模拟属性注入。

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

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

【问题讨论】:

    标签: c# unit-testing nunit autofac automoq


    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多