Rhino moq Property.value约束

时间:2011-05-08 15:03:42

标签: rhino-mocks

我的跟随直接测试没有通过(虽然我觉得应该)。要么我缺少某些东西,要么不清楚Property.value约束。请帮助我理解property.value约束的概念。

public interface ISomeInterface
{
     void SomeMethod(string x, string y);
}

公共类SomeClassTest     {

[Test]

public void SomeMethodTest()
    {

        MockRepository mocks = new MockRepository();
        ISomeInterface mockservice = mocks.StrictMock<ISomeInterface>();
        using (mocks.Record())
        {
            mockservice.SomeMethod("xValue", "yValue");
            LastCall.Constraints(Property.Value("x", "xValue"),
                                 Property.Value("y", "yValue"));
        }
        mockservice.SomeMethod("xValue", "yValue");
        mocks.Verify(mockservice);
    }
}

提出异常:

Rhino.Mocks.Exceptions.ExpectationViolationException:ISomeInterface.SomeMethod(“xValue”,“yValue”);预期#0,实际#1。 ISomeInterface.SomeMethod(属性'x'等于xValue,属性'y'等于yValue);预期#1,实际#0。

2 个答案:

答案 0 :(得分:1)

我建议您使用以下语法(AAA syntax):

// arrange
var mockservice = MockRepository.GenerateMock<ISomeInterface>();

// act
mockservice.SomeMethod("xValue", "yValue");

// assert
mockservice.AssertWasCalled(
    x => x.SomeMethod("xValue", "yValue")
);

答案 1 :(得分:0)

此示例类说明了使用适当的属性调用断言方法的选项:

public class UsesThing
{
   private IMyThing _thing;

   public UsesThing(IMyThing thing)
   {
      _thing = thing;
   }

   public void DoTheThing(int myparm)
   {
      _thing.DoWork(myparm, Helper.GetParmString(myparm));
   }

   public void DoAnotherThing(int myparm)
   {
       AnotherThing thing2 = new AnotherThing();
       thing2.MyProperty = myparm + 2;
       _thing.DoMoreWork(thing2)
    }
}

对断言使用简单值可能适用于使用值类型的DoTheThing方法:

[Test]
public void TestDoTheThing()
{
    IMyThing thing = MockRepository.GenerateMock<IMyThing>();
    UsesThing user = new UsesThing(thing);

    user.DoTheThing(1);

    thing.AssertWasCalled(t => t.DoWork(1, "one");
}

但是,如果您需要在方法中创建一个对象并将其作为参数传递,就像在DoAnotherThing方法中那样,这种方法将不起作用,因为您没有对该对象的引用。您必须检查未知对象的属性值,如下所示:

[Test]
public void TestDoAnotherThing()
{
    IMyThing thing = MockRepository.GenerateMock<IMyThing>();
    UsesThing user = new UsesThing(thing);

    user.DoAnotherThing(1);

    thing.AssertWasCalled(t => t.DoMoreWork(null), t => t.IgnoreArguments().Constraints(Property.Value("MyProperty", 3))));        
}

新的Rhino语法如下所示,但是当我使用它时,我崩溃了VS 2008:

thing.AssertWasCalled(t => t.DoMoreWork(Arg<AnotherThing>.Matches(Property.Value("MyProperty", 3))));