开发者

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. Coul开发者_JS百科d 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?


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));


The best answer is to use a mocking framework as others here have mentioned. The dirty way, but sometimes faster if you don't want to learn mocking frameworks (which you really should) is to create a test class and override virtual methods. In your case something like

public class RepoUnderTest : Repo
{
    public bool UpdateRegistrationDetailsCalled = false;
    public override void UpdateRegistrationDetails(Car car)
    {
        base.UpdateRegistrationDetails(car);
        UpdateRegistrationDetailsCalled = true;
    }
}

then you can test something similar to

[HttpPost]
public ActionResult Create(Car car)
{
   // Arrange
   var _repository = new RepoUnderTest();

   // Act
   _repository.CreateCar(car);

   // Assert
   Assert.IsTrue(_repository.UpdateRegistrationDetailsCalled);
}

Again a mocking framework is best. And I'd vote for those, but sometimes this is an easy introduction to testing for these things before you get heavier into mocking.


Regarding using of Expect() in RhinoMocks. I preffer to use stubs and 'Stub()' or AssertWasCalled() methods as much as possible. Expect() is used in cases when nothing else works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜