【问题标题】:mock problem模拟问题
【发布时间】:2009-06-11 06:28:28
【问题描述】:

//IsExist 总是假的,是不是bug?

  [TestMethod]
   public void IsExist()
   {
       private Mock<IRepository> repository = new Mock<IRepository>();
                   Foo f = new Foo();
                   repository.Expect(s => s.IsExist(foo)).Returns(true);
       var controller = new MyController(repository.Object);
       var result = (ViewResult)controller.DoSometing();

   }

           public class MyController : Controller
           {

           IRepository _repository ;

           public MyController(IRepository repository)
   {
       _repository = repository;

   }

           public ViewResult DoSometing()
   {
       bool IsExist = _repository.IsExist(new Foo());
                   //IsExist always false,is it a bug?
       return View(foo);
   }

           }

【问题讨论】:

    标签: unit-testing mocking


    【解决方案1】:

    首先,您使用的是哪个模拟库(答案可能会因此而改变)?

    我知道如果您使用的是 Rhino Mocks,问题将是您的期望设置为在接收到您在顶部创建的 foo 的特定实例时返回 true。这与在控制器中执行时传入的实例不同,因此它返回 false(因为没有针对 foo 对象的 that 版本设置期望)。更清楚地说,如果你有这个代码:

    Foo f1 = new Foo();
    Foo f2 = new Foo();
    repository.Expect(s => s.IsExist(f1)).Returns(true);
    bool b1 = repository.Object.IsExist(f1);
    bool b2 = repository.Object.IsExist(f2);
    

    我希望b1 为真(因为这是您设置的特定期望,即给定f1 返回true)和b2 为假(因为您没有告诉存储库如果收到f2,则执行任何特定操作,因此它将回退到返回 false 的默认行为。

    在 Rhino Mocks 中,您需要像这样设置期望:

    repository.Expect(s => s.IsExist(Arg<Foo>.Is.TypeOf)).Returns(true);
    

    如果使用 Foo 对象的 any 实例调用 IsExist,则返回 true。如果你需要更具体,你可以有这样的东西:

    repository.Expect(s => s.IsExist(f => f.SomeProperty == "blah" && f.OtherProperty.StartsWith("baz")))).Returns(true);
    

    如果foo.SomeProperty 等于"blah"foo.OtherProperty"baz" 开头,则返回true。

    看起来您使用的不是 Rhino Mocks,因为您的语法有点不同,但希望这可以为您指明正确的方向...

    【讨论】:

      【解决方案2】:

      在检查它是否存在之前,用一些值初始化你的对象属性。

       public ViewResult DoSometing()
         {
             Foo obj = new Foo();
             obj.Property1 = "some value";
             bool IsExist = _repository.IsExist(obj);
                         //IsExist always false,is it a bug?
             return View(foo);
         }
      

      【讨论】:

        猜你喜欢
        • 2011-04-25
        • 2012-07-19
        • 2011-11-06
        • 2011-08-24
        • 2015-11-13
        • 2017-02-03
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        相关资源
        最近更新 更多