Search code examples
c#unit-testingrhino-mockspartial-mocks

How can I assert a method is called without executing the code within the method?


Imagine that we have below code

public class test
  {
   public void Condition(x,y)
   {
       if (x == y)
       {
           methodOne();
       }
       else
       {
           methodTwo();
       }
   }
    public void methodOne(){//do some database stuff}
    public void methodTwo(){//do some database stuff}
 }

I want to assert that if methodone is get called when x==y or not but do not want my test to execute the code inside my method one as it will do some database stuff ...

I am writing something like this

 MockRepository mockRepository=new MockRepository();
 var Mock = mockRepository.PartialMock<test>();
 mock.Replay();
 mock.condition(1,1);
 mock.AssertWasCalled(x=>x.methodOne);
 mock.VerifyAllExpectations();

but it tries to run run the stuff in the method one as well and I do not want my test do the database connection , I just need to make sure my condition is work and it called or not.


Solution

  • You are mixing your concerns, business logic and data access, in one class. You need to think about Single Responsibility Principle and Separation of concerns.

    Your public void Condition(x,y) should probably be in a Business Logic Layer with methodOne() and methodTwo() being in a Data Access Layer.

    The Data Access Layer should be injected (IoC) into the Business Logic Layer so it can be mocked out. That way when you are testing the Condition method you would pass in a mock Data Access Layer that doesn't actually connect to a database.

    That way you can check that Condition was called, as you are now, without any side-effects like writing to the database. When you encounter situations like this it helps you to break out your code into a better architecture and could ultimately lead you to investigate Test Driven Development.