Question

I was playing around with testing using machine specifications and there is something that i am just not able to do, was wondering if somebody have been there before,

Is there any way to using Rhino Mocks to create a stub for a method that uses a lambda expression, i found that i can do the following

Having this method in a sample class:

public void UpdateVisit(int userId){
    var user = repository.FindBy<User>(x=>x.Id==userId && user.IsActive ==true);
    user.Visit = user.Visit + 1;
    repository.Save(user);
}

I can stub the method like this:

//...Inside test method
var user = new User();
repository.Stub(x=>x.FindBy<User>(Arg<Expression<Func<User,bool>>>.Is.Anything)).Return(user);

The thing is I would like to stub the method not to Any Lambda Expression, just for the specific lambda expression "x=>x.Id==userId && user.IsActive ==true", so that the test would fail if this expression changes in the method...

I guess i could create a mock repository that does not go to the database and test the behavior in the lambda though this, i was wondering if there is another approach to this...

Appreciate any suggestions on this, Thanks

Was it helpful?

Solution

You don't want to test that the particular lambda expression is used in the method. You want to test the behavior that the method is suppose to have. Testing implementation details like a specific lambda expression is in general too brittle. Instead:

[Fact]
UpdateVisit_updates_Visit_for_user_that_is_in_the_repository_and_is_active() {
    // set up mock repository with dummy user having
    // userId == 1,
    // IsActive == true,
    // Visit = 42
    // invoke UpdateVisit
    // pull userId == 1 from the repository
    Assert.Equal(43, user.Visit);
}

[Fact]
UpdateVisit_does_not_update_visit_for_user_that_is_not_active() {
    // etc.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top