Search code examples
c#asp.netunit-testingxunitfakeiteasy

FakeItEasy mocks stuff automatically


So i was writing xUnit tests for my Asp.net Web Api application using FakeItEasy. Here is my Test which should return a List of MemberDto objects;

       public async Task UsersController_GetUsers_ReturnsOK()
        {
            //Arrange

            //var users = A.Fake<IEnumerable<MemberDto>>();
            //A.CallTo(() => _userRepository.GetMembersAsync(A<string>.That.Matches(email => true))).Returns(users);

            //Act
            var result = await _controller.GetUsers();

            //Assert
            result.Should().NotBeNull();
            result.Should().BeOfType<ActionResult<IEnumerable<MemberDto>>>();
            result.Result.Should().BeOfType<OkObjectResult>();
        }
}

The Implementation of GetUsers method in controller:

{
    public async Task<ActionResult<IEnumerable<MemberDto>>> GetUsers()
    {   
        var currentUser = await _userRepository.GetUserByEmailAsync(_userExtensions.GetEmail(User));
        users = await _userRepository.GetMembersAsync(currentUser.Email);

        return Ok(users);
    }
}

As you can see i have commented out the line in xUnit test where it mocks the GetMembersAsync method from _userRepository but it fakes the data anyway (users aren't null, it will have type of Faked System.Collection...)

That's it, could someone explain it to me. It's my first time writing unit tests, i've been watching a guy called Teddy Smith on YouTube where he explained how to write them. I downloaded his example lesson from his github and did the same thing with commenting out the line with mocking and It did pass the test, nothing has changed no matter the line is there or not. Thanks


Solution

  • FakeItEasy comes with a set of default behaviours that were thought by the developers to be useful. So members with return values will by default return something (specifically a "Dummy", a non-null object of the relevant type).

    In the case of an IEnumerable, the Dummy will be a thing that looks like an enumerable whose members themselves return more Dummies. In this case, it would return a Dummy enumerator whose MoveNext returns a Dummy boolean (which is false, so GetMembersAsync returns something that looks like an empty enumerable.

    You can read more at Default fake behavior → Overrideable members are faked.