如何根据lambda参数从存根返回不同的值

时间:2012-01-03 16:07:01

标签: c# .net rhino-mocks

我有以下示例测试代码

    public Stage Test(Stage Stage)
    {
        var StartStage = StageRepository.Single(x => x.Order == 1);
        var EndStage = StageRepository.Single(x => x.Order == 5);
        var ErrorStage = StageRepository.Single(x => x.Name == "Error");

        if (Stage == StartStage)
        {
            return EndStage;
        }
        else
        {
            return ErrorStage;
        }
    }

我正在尝试使用以下单元测试来测试它

    [TestMethod]
    public void XXXTest()
    {
        //// Arrange
        var AutoMocker = new RhinoAutoMocker<StageService>(MockMode.AAA);

        MockRepository mockRepository = new MockRepository();

        var MockStageRepository = AutoMocker.Get<IRepository<Stage>>();

        Stage StartStage = mockRepository.Stub<Stage>();
        StartStage.Order = 1;

        Stage EndStage = mockRepository.Stub<Stage>();
        EndStage.Order = 5;

        Stage ErrorStage = mockRepository.Stub<Stage>();
        ErrorStage.Name = "Error";

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> StartParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(StartParam)))
            .Return(StartStage);

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> EndParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(EndParam)))
            .Return(EndStage);

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> ErrorParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(ErrorParam)))
            .Return(ErrorStage);

        StageService StageService = AutoMocker.ClassUnderTest;


        //Act
        var ReturnStage = StageService.Test(StartStage);


        //Assert
        Assert.AreEqual(ReturnStage, EndStage);
    }

然而,这不起作用,因为当我调用StageRepository.Single()时它没有返回任何内容。如果我更改存根代码以忽略该参数,那么它确实会返回一些东西,但它将是每次调用Single()时返回的相同对象,我不想要。

是否可以配置RhinoMocks,以便根据传递给它的lambda从存根中返回不同的对象?

2 个答案:

答案 0 :(得分:1)

如果linq条件不重要,我建议将其匹配为任何类似的东西

repository.Stub(x => x.Find(Arg<System.Linq.Expressions.Expression<Func<Entity, bool>>>.Is.Anything)).Return(entitiesList.AsQueryable());

希望得到这个帮助。

答案 1 :(得分:0)

谢谢你。这是一种享受。我缺少的一件事是ExpressionTree上的Compile方法。您的示例代码中存在一个小错误(您使用x两次)。为了完整起见,这是工作代码。

        MockStageRepository2
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Matches(y => y.Compile()(StartStage2))))
            .Return(StartStage2);