Home > Software design >  Mocking a function with optional parameter with fixed parameter using Nsubstitute in C# returns null
Mocking a function with optional parameter with fixed parameter using Nsubstitute in C# returns null

Time:03-17

I have been trying to mock a function that included optional parameters with fixed parameters but every time I am getting a null value here is my function defined in interface which I want to mock:

List<object> GetEntitiesByIDs(List<long> ids, bool includeStatuses = false, bool includeRounds = false, bool includeSample = false);

Method calling this function:

        public object ExportSpecimens(List<long> ids)
        {
            var specimens = Repo.GetEntitiesByIDs(ids, includeSample: true);
        }

Here is my test method:

        public void ExportSpecimens_ValidData_Success()
        {
             var _repo = Substitute.For<IRepo>();
            _repo.GetEntitiesByIDs(Arg.Any<List<long>>(), includeSample: Arg.Any<bool>()).Returns(_specimens);

        }

whenever I am hitting the function in ExportSpecimens I am getting null value. I also tried to include all the parameters in both the test and main function but it didn't work. but I have noticed some ambiguity after hitting the function GetEntitiesByIDs first time in ExportSpecimens I am getting null value and then I hit it again by scrolling up the debugger point or in immediate windows I am getting correct input.

I am not able to understand how can I mock this function without any issue?

CodePudding user response:

I am not able to find anything in which I can have a better understanding of the solution to my question. However, for now, to move my work forward I have come to a workaround in which I have created an overloaded function with the fixed parameters which I am able to mock successfully.

For example:

I want to mock this function:

List<object> GetEntitiesByIDs(List<long> ids, bool includeStatuses = false, bool includeRounds = false, bool includeSample = false);

Instead of directly mocking it I have created an another function which calling this main function:

List<object> GetEntitiesByIDs(bool includeSample, List<long> ids){
   GetEntitiesByIDs(ids, includeSample: includeSample)
}

and it worked like a charm!

  • Related