【问题标题】:Unit testing ensure one method calls another method单元测试确保一种方法调用另一种方法
【发布时间】:2011-07-10 22:35:16
【问题描述】:
[HttpPost]
public ActionResult Create(Car car)
{
   _repository.CreateCar(car);
   _repository.UpdateRegistrationDetails(car);
}

我想做的是编写单元测试以确保Create 调用CreateCarUpdateRegistrationDetails。这些方法中发生的事情并不重要,只是它们被调用。有人可以告诉我该怎么做吗?我需要为此使用模拟框架吗?我安装了 RhinoMocks 以供使用。你在 RhinoMocks 中使用Expect 吗?

【问题讨论】:

    标签: asp.net-mvc unit-testing model-view-controller mocking rhino-mocks


    【解决方案1】:

    再次使用 Moq 我认为您需要模拟存储库(当然这里假设名称)

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

    不需要SetupExpect,因为模拟方法不返回任何内容

    [编辑] 这是一个 Rhino.Mocks 示例

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

    【讨论】:

    • 还要确保_repository 是一个接口或者两个方法都是虚拟的
    【解决方案2】:

    最好的答案是使用这里其他人提到的模拟框架。肮脏的方式,但如果你不想学习模拟框架(你真的应该),有时更快的是创建一个测试类并覆盖虚拟方法。在你的情况下,像

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

    然后你可以测试类似的东西

    [HttpPost]
    public ActionResult Create(Car car)
    {
       // Arrange
       var _repository = new RepoUnderTest();
    
       // Act
       _repository.CreateCar(car);
    
       // Assert
       Assert.IsTrue(_repository.UpdateRegistrationDetailsCalled);
    }
    

    同样,模拟框架是最好的。我会投票给那些,但有时这是一个简单的介绍,可以在你开始大量嘲笑之前测试这些东西。

    【讨论】:

      【解决方案3】:

      关于在 RhinoMocks 中使用Expect()。我更喜欢尽可能使用存根和 'Stub()' 或 AssertWasCalled() 方法。 Expect() 用于没有其他方法的情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-10
        • 2010-12-22
        • 2020-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多