Question

I'm trying to test a data access class. Basically, function1 is reading data directly from DataContext, and the other function2 is adding filters. function1 and function2 can be in same class or inherit class.

How can I stub function1's return value and test function2?

Sample code I got this far, but it doesn't work. I have tried to use Rhino Mocks, and StructureMap Auto Mock, still getting errors when stub.

Any help is appreciated. Thanks a lot.

public class TestClass : ITestClass
{
    private DbContext _context;

    public IEnumerable<TestObject1> TestFunction1()
    {
        return _context.GetSomething();
    }

    public TestObject2 TestFunction2()
    {
        return TestFunction1().Where(x=>x.Parent == null);
    }
}
public interface ITestClass
{
    IEnumerable<TestObject1> TestFunction1();
    TestObject2 TestFunction2();
}
[Test]
public void TestFunction2_Test()
{
    var mock = MockRepository.GenerateMock<TestClass>();

    var test = new List<TestObject1>();

    mock.Stub(x=>x.TestFunction1()).Return(test);

    var result = mock.TestFunction2();

    Assert.AreSame(1, result.Count());
}
Was it helpful?

Solution

What you need in order to get this to work is a "partial mock". Rhino Mocks can only stub virtual methods when performing partial mocks. If you mark TestFunction1 as virtual it should work.

Also you should use Assert.AreEqual, since it checks for value equality ("are the objects equivalent?"). Assert.AreSame checks for reference equality ("are they the same object?"). See this answer for further explanation.

Regarding partial mocks in general, they should be avoided. Having to perform partial mocks is often an indication that the class is trying to do too much. Either test the function as part of a unit test of the class, or extract it to a separate collaborating class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top