Different return values the first and second time with Moq

后端 未结 7 635
感动是毒
感动是毒 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:09

    The accepted answer, as well as the SetupSequence answer, handles returning constants.

    Returns() has some useful overloads where you can return a value based on the parameters that were sent to the mocked method. Based on the solution given in the accepted answer, here is another extension method for those overloads.

    public static class MoqExtensions
    {
        public static IReturnsResult ReturnsInOrder(this ISetup setup, params Func[] valueFunctions)
            where TMock : class
        {
            var queue = new Queue>(valueFunctions);
            return setup.Returns(arg => queue.Dequeue()(arg));
        }
    }
    

    Unfortunately, using the method requires you to specify some template parameters, but the result is still quite readable.

    repository
        .Setup(x => x.GetPageByUrl(path))
        .ReturnsInOrder(new Func[]
            {
                p => null, // Here, the return value can depend on the path parameter
                p => pageModel.Object,
            });
    

    Create overloads for the extension method with multiple parameters (T2, T3, etc) if needed.

提交回复
热议问题