Search code examples
asp.net-mvcunit-testingmodel-view-controllermockingrhino-mocks

Unit testing ensure one method calls another method


[HttpPost]
public ActionResult Create(Car car)
{
   _repository.CreateCar(car);
   _repository.UpdateRegistrationDetails(car);
}

What I'm wanting to do is write unit test to ensure that Create calls CreateCar and UpdateRegistrationDetails. It doesn't matter about what happens in these methods but just that they get called. Could someone please tell me how to do this? Do I need to use a mocking framework for this? I have RhinoMocks installed to use. Do you use the Expect in RhinoMocks?


Solution

  • Again using Moq I think you need to mock the Repository instead (assuming names here of course)

    var mock = new Mock<IRepository>();
    
    var controller = new Controller(mock.Object); //assuming this is how you create it
    
    var car = new Car();
    controller.Create(car);
    
    mock.Verify(x => x.CreateCar(car));
    mock.Verify(x => x.UpdateRegistrationDetails(car));
    

    No need for Setup or Expect as the mocked methods do not return anything

    [EDIT] Here is a Rhino.Mocks example

    var mock = MockRepository.GenerateStub<IRepository>();
    
    var controller = new Controller(mock); //assuming this is how you create it
    
    var car = new Car();
    controller.Create(car);
    
    mock.AssertWasCalled(x => x.CreateCar(car));
    mock.AssertWasCalled(x => x.UpdateRegistrationDetails(car));