I am using xUnit and trying to unit test my WebAPI controller below:
public IHttpActionResult Post(UserSearchRequest userSearchRequest)
{
int? numberOfRecords;
var users = this._userRepository.Search(userSearchRequest, out numberOfRecords).AsEnumerable();
return this.Ok(new { users, numberOfRecords });
}
And my test is below:
[Fake]
public User User { get; set; }
[Fake]
public UserSearchRequest UserSearchRequest { get; set; }
[Fake]
public IRepository<User> UserRepository { get; set; }
[UnderTest]
public UsersSearchController UsersSearchController { get; set; }
public UsersSearchControllerTests()
{
Fake.InitializeFixture(this);
}
[Fact]
public void Get_WithUserSearchRequest_ExpectCallToUserRepositoryAndCorrectResultsReturned()
{
int? numberOfRecords = 0;
var users = new[] { this.User }.AsQueryable();
A.CallTo(() => this.UserRepository.Search(A<UserSearchRequest>.Ignored, out numberOfRecords))
.Returns(users)
.AssignsOutAndRefParameters(users.Count());
var actionResult = this.UsersSearchController.Post(this.UserSearchRequest);
var response = actionResult as OkNegotiatedContentResult<object[]>;
Assert.NotNull(response);
int? numberOfRecordsReturned = int.Parse(response.Content[1].ToString());
Assert.Equal(users.Count(), numberOfRecordsReturned);
}
The mocked call to the repository seems to work fine when I debug into the controller, however when the method returns my actionResult is null. Therefore the response is also null etc.
Now I have a similar controller and test and that works fine with the main difference being that the controller does not return an array of objects but a single collection (i.e. the accounts but not how many records were found).
When running this it works fine, so in my mind I am feeling that something is wrong with the mocking of the objects and how they are handled by the response when wrapped into an object array.
Am I doing something wrong here? Or is there an issue with FakeItEasy?