Different return values the first and second time with Moq

后端 未结 7 619
感动是毒
感动是毒 2021-01-29 18:51

I have a test like this:

    [TestCase("~/page/myaction")]
    public void Page_With_Custom_Action(string pat         


        
7条回答
  •  隐瞒了意图╮
    2021-01-29 19:10

    You can use a callback when setting up your mock object. Take a look at the example from the Moq Wiki (http://code.google.com/p/moq/wiki/QuickStart).

    // returning different values on each invocation
    var mock = new Mock();
    var calls = 0;
    mock.Setup(foo => foo.GetCountThing())
        .Returns(() => calls)
        .Callback(() => calls++);
    // returns 0 on first invocation, 1 on the next, and so on
    Console.WriteLine(mock.Object.GetCountThing());
    

    Your setup might look like this:

    var pageObject = pageModel.Object;
    repository.Setup(x => x.GetPageByUrl(path)).Returns(() => pageObject).Callback(() =>
                {
                    // assign new value for second call
                    pageObject = new PageModel();
                });
    

提交回复
热议问题