Search code examples
c#nmock

NMock Method Mixing WithArguments and WithAnyArguments


Performing unit testing I had a mistake mocking a method. I am trying to return different results depending on the Parameters to input and otherwise return a default answer. The problem is that always I am receiving the default answer.

_commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
            .WithAnyArguments().WillReturn(-1);
        _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("",false,null))
            .With("BAG1", true, FamilyFaresType.Optima).WillReturn(0);
        _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
            .With("BAG2", true, FamilyFaresType.Optima).WillReturn(87);
        _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
            .With("BAG3", true, FamilyFaresType.Optima).WillReturn(139);

Solution

  • The error lies in the order of the lines. The line returns the default "WithAnyArguments" must be after the definitions with arguments "With".

                _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("",false,null))
                .With("BAG1", true, FamilyFaresType.Optima).WillReturn(0);
            _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
                .With("BAG2", true, FamilyFaresType.Optima).WillReturn(87);
            _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
                .With("BAG3", true, FamilyFaresType.Optima).WillReturn(139);
            _commonFunctionsMock.Expects.AtLeastOne.Method(x => x.GetFeePrice("", false, null))
                .WithAnyArguments().WillReturn(-1);