Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a dependent property with 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?

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

     }

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...

like image 866
jparram Avatar asked Apr 15 '11 20:04

jparram


1 Answers

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.

like image 54
rsbarro Avatar answered Sep 28 '22 04:09

rsbarro