Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a mock has setup for a member?

Tags:

c#

moq

I have a need for doing:

if(!fooMock.HasSetupFor(x => x.Bar))
{
    fooMock.Setup(...);
}

Above is pseudocode and it is the equivalent of HasSetupFor I'm looking for. Is this possible?

like image 359
Johan Larsson Avatar asked Dec 07 '16 15:12

Johan Larsson


People also ask

How do you know if a method is called mock?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

How can we use a MOQ to check if a method is called with the correct parameters?

When you need to verify that the code under test called a method with the expected parameters, you can mock the method with Moq and use Verify() + It.Is<T>() to check the parameters passed in. Verify() asserts that the method call happened as expected with the specified parameters.


1 Answers

This might be possible with the MockBehavior.Strict. I created proof of concept.

    [TestClass]
    public class UnitTest1
    {
        public interface ITestInterface
        {
            int Bar { get; set; }
            void Foo(int foo);
        }


        [TestMethod]
        public void TestMethod1()
        {
            Mock<ITestInterface> mock = new Mock<ITestInterface>(MockBehavior.Strict);
            mock.Setup(a => a.Foo(3));
            mock.Setup(a => a.Bar)
                .Returns(3);


            bool t1 = mock.HasSetupFor((m) => m.Foo(3));
            bool t2 = mock.HasSetupFor((m) => m.Bar);
        }
    }

    public static class MockExtension
    {
        public static bool HasSetupFor<T>(this Mock<T> value, Action<T> expression) where T : class
        {
            if (value.Behavior != MockBehavior.Strict)
                throw new InvalidOperationException("Behaviour must be strict");

            bool hasSetup = true;

            try
            {
                expression(value.Object);
            }
            catch(MockException)
            {
                hasSetup = false;
            }

            return hasSetup;
        }

        public static bool HasSetupFor<TMock, TResult>(this Mock<TMock> value, Func<TMock, TResult> expression) where TMock : class
        {
            if (value.Behavior != MockBehavior.Strict)
                throw new InvalidOperationException("Behaviour must be strict");

            bool hasSetup = true;

            try
            {
                TResult tmp = expression(value.Object);
            }
            catch (MockException)
            {
                hasSetup = false;
            }

            return hasSetup;
        }
    }
like image 158
Johnny Avatar answered Oct 06 '22 17:10

Johnny