用Moq模拟从属属性

| 如果我的类具有通过属性注入解决的依赖关系,是否可以使用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并点击使用该服务的行时,就使用了模拟...     
已邀请:
我可能会误解并简化了这个问题,但是我认为下面的代码应该可以工作。由于您拥有
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;
        }
    }
}
希望能有所帮助。如果我想念某些东西,请告诉我,我会看看我能做什么。     

要回复问题请先登录注册