用Moq模拟依赖属性

本文关键字:属性 依赖 模拟 Moq | 更新日期: 2023-09-27 17:50:23

如果我有一个类,有一个依赖关系是通过属性注入解决的,是否可以使用Moq来模拟该属性的行为?

    public class SomeClass
     {
        //empty constructor
        public SomeClass() {}
        //dependency
        public IUsefuleService Service {get;set;}
        public bool IsThisPossible(Object someObject)
        {
           //do some stuff
           //I want to mock Service and the result of GetSomethingGood
           var result = Service.GetSomethingGood(someObject);
        }
     }

所以,someeclass正在测试中,我试图弄清楚我是否可以模拟IUsefulService的Moq行为,所以当我测试IsThisPossible和使用服务的行被击中时,模拟被使用…

用Moq模拟依赖属性

我可能误解并过度简化了这个问题,但我认为下面的代码应该可以工作。由于您将Service属性作为公共属性,因此您可以模拟IUsefulService,新建SomeClass,然后将SomeClass上的Service属性设置为您的模拟。

using System;
using NUnit.Framework;
using Moq;
namespace MyStuff
{
    [TestFixture]
    public class SomeClassTester
    {
        [Test]
        public void TestIsThisPossible()
        {
            var mockUsefulService = new Mock<IUsefulService>();
            mockUsefulService.Setup(a => a.GetSomethingGood(It.IsAny<object>()))
                .Returns((object input) => string.Format("Mocked something good: {0}", input));
            var someClass = new SomeClass {Service = mockUsefulService.Object};
            Assert.AreEqual("Mocked something good: GOOD!", someClass.IsThisPossible("GOOD!"));
        }
    }
    public interface IUsefulService
    {
        string GetSomethingGood(object theObject);
    }
    public class SomeClass
    {
        //empty constructor
        public SomeClass() { }
        //dependency
        public IUsefulService Service { get; set; }
        public string IsThisPossible(Object someObject)
        {
            //do some stuff
            //I want to mock Service and the result of GetSomethingGood
            var result = Service.GetSomethingGood(someObject);
            return result;
        }
    }
}

希望有帮助。如果我遗漏了什么,请告诉我,我会看看我能做什么。