GodsCrimeScene
GodsCrimeScene

Reputation: 1270

Rhinomocks stub method

Is it possible to stub out 1 method much like shimming in Microsoft Fakes?

In this case I would like to stub the DB call, but continue with the rest of my method logic.

public class Network
{
    public string GetUsers()
    {
       User users = GetUsersFromDB();
       return users.Formatted();
    }

Test:

Network network = MockRepositiory.GenerateStub<Network>();

network.Stub(x => x.GetUsersFromDB()).Return(myTestUserObject);

string result = network.GetUsers();

Assert.AreEqual(expected, result);

Upvotes: 1

Views: 1106

Answers (1)

Alexander Stepaniuk
Alexander Stepaniuk

Reputation: 6408

Most likely the reason why you are failing to setup stub for GetUsersFromDB() is that this method is not virtual or not public.
So you can made it public virtual and setup the stub.

But it is probably much better if you adjust the class according to single responsibility principle and extract DB access code into a separate class with some interface like IDbAccess, e.g.

interface IDbAccess
{
    User GetUsersFromDB();
}

Then you can inject interface as a dependency into Network class and use it there instead of use DB access method member.
As a result, for test purpose you may just stub injected interface IDbAccess and run tests with no need to generate stubs for tested class, i.e. Network.

Upvotes: 3

Related Questions