用Moq嘲笑一个依赖的财产

时间:2011-04-15 20:57:07

标签: c# unit-testing moq

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

e.g。

    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并且使用该服务的行被命中时,使用了mock ...

1 个答案:

答案 0 :(得分:7)

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

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

希望有所帮助。如果我遗失某些东西让我知道,我会看到我能做些什么。