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?
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With