Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino Mocks, VerifyAllExpectations

I would like to track a call to a method with Rhino Mocks. Let's assume I have this code:

public class A
{
    protected IB _b;

    public A(IB b)
    {
        _b = b;
    }

    public void Run( string name )
    {            
        _b.SomeCall(new C { Name = name });
    }
}    

public interface IB
{
    void SomeCall( C c );
}    

public class C
{
    public string Name { get; set; }
    // more attributes here
}

And the test looks like:

// prepare
var bMock = Rhino.Mocks.MockRepository.GenerateStrictMock<IB>();
bMock.Expect(x => x.SomeCall(new C { Name = "myname" }));
var sut = new A(bMock);

// execute
sut.Run("myname");

// assert
bMock.VerifyAllExpectations();

The test fails with a ExpectedViolationException because Rhino Mocks framework detects 2 distinct C classes.

How do I check the call if the subject under tests creates the object parameter into the method under test? Any chance to tell Rhino Mocks to check the parameter as "Equals"?

Thanks a ton!

like image 379
Jordi Avatar asked Aug 24 '12 07:08

Jordi


2 Answers

I recommend you use the much easier (and more maintainable) AAA syntax. In most cases, strict mocks are more of a pain than anything else.

the arguments are compared using Equals. If C doesn't override Equals, it is compared by reference and won't match in your case. Use Matches to check the argument in some other way.

// arrange
var bMock = MockRepository.GenerateMock<IB>();
var sut = new A(bMock);

// act
sut.Run("myname");

// assert
bMock.AssertWasCalled(x => x.SomeCall(Arg<C>.Matches(y => y.Name == "myname"));
like image 53
Stefan Steinegger Avatar answered Nov 05 '22 02:11

Stefan Steinegger


You need to add IgnoreArguments and can additionally add parameter contraints for the call to 'SomeCall':

bMock.Expect(x => x.SomeCall(new C { Name = "myname" }))
    .IgnoreArguments()
    .Constraints(new PropertyConstraint(typeof(C), "Name", 
        Rhino.Mocks.Constraints.Is.Equal("myname")));
like image 2
Franky Avatar answered Nov 05 '22 00:11

Franky