本文介绍了使用 Moq 模拟依赖属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a class that has a dependency that is resolved via property injection, is it possible to Mock the behavior of that property using 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);
        }

     }

所以,SomeClass 正在测试中,我想弄清楚我是否可以用 Moq 模拟 IUsefulService 的行为,所以当我测试 IsThisPossible 并且使用该服务的行被命中时,使用模拟...

So, SomeClass is under test and I am trying to figure out if I can mock the behavior of IUsefulService with Moq so when I test IsThisPossible and the line using the service is hit, the mock is used...

推荐答案

我可能误解并过于简化了问题,但我认为下面的代码应该可以工作.由于您将 Service 属性作为公共属性,您可以模拟 IUsefulService,新建 SomeClass,然后设置 ServiceSomeClass 上的 属性添加到您的模拟中.

I may be misunderstanding and oversimplifying the question, but I think code below should work. Since you have the Service property as a public property, you can just mock IUsefulService, new up SomeClass, and then set the Service property on SomeClass to your mock.

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

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

Hope that helps. If I'm missing something let me know and I'll see what I can do.

这篇关于使用 Moq 模拟依赖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 19:08