I am having an issue setting up the return value in my unit test causing unexpected data to be returned on second execution.
I am testing a service I have created and I have the following code to setup the return data from an interface used within the service.
_dataService.Setup(x => x.GetJsonFromApi(It.IsAny<string>(), API_KEY, ENTITY_A))
.Returns(Task.FromResult(new List<Entity>() {
new Entity {
Forename = "first_name",
Surname = "last_name",
EntityType = ENTITY_A
}
}));
_dataService.Setup(x => x.GetJsonFromApi(It.IsAny<string>(), API_KEY, ENTITY_B))
.Returns(Task.FromResult(new List<Entity>() {
new Entity {
Forename = "first_name",
Surname = "last_name",
EntityType = ENTITY_B
}
}));
_dataService.Setup(x => x.GetJsonFromApi(It.IsAny<string>(), API_KEY, ENTITY_C))
.Returns(Task.FromResult(new List<Entity>() {
new Entity {
Forename = "first_name",
Surname = "last_name",
EntityType = ENTITY_C
}
}));
The above works fine on the first execution of my service in the unit test with each call returning one object. The code in the service is:
var data = await _apiDataService.GetJsonFromApi(apiUrl, apiKey, ENTITY_A);
data.AddRange(await _apiDataService.GetJsonFromApi(apiUrl, apiKey, ENTITY_B));
data.AddRange(await _apiDataService.GetJsonFromApi(apiUrl, apiKey, ENTITY_C));
On the second execution; the first call (e.g. _apiDataService.GetJsonFromApi(apiUrl, apiKey, ENTITY_A)) is returning a list of three objects instead of the expected one. I allowed the debugger to continue execute of the following two calls with data.AddRange() and the expected single object is returned from both of those on the second execution and added to the list so I end up with five objects.
Is anyone able to tell me what I am doing wrong please.
Some additional info:
The code is executed twice in the unit test method as:
apiCheckerService.AddEntitiesHash(client.Id).GetAwaiter().GetResult();
apiCheckerService.AddEntitiesHash(client.Id).GetAwaiter().GetResult();
The properties passed to the GetJsonFromApi method are all strings and the ENTITY_A, ENTITY_B and ENTITY_C are constants, so on the second execution all parameters passed to the function should be exactly the same.
I am testing another part of the service that should be locked down on the second run, but need this to run properly for the test to progress.