FakeItEasy:模拟方法没有返回预期结果

时间:2015-08-18 08:25:49

标签: c# unit-testing mocking fakeiteasy

我在单元测试中使用FakeItEasy作为模拟框架。方法fakeUserService.AddUser被模拟为返回新的MwbeUser对象,其中包含方法AddUser中的一些非空值

 A.CallTo(() => fakeUserService.AddUser(new MwbeUserRegistrationIn() 
                                            { 
                                                UserName = userName,                                                               
                                                FirstName = firstName, 
                                                SecondName = secondName, 
                                                Password = passwd, 
                                                Email = email, 
                                                BirthDate = birthdate 
                                            })).Returns(new MwbeUser 
                                                            { 
                                                                UserName = userName, 
                                                                Email = email, 
                                                                FirstName = firstName, 
                                                                SecondName = secondName, 
                                                                BirthDate = birthdate 
                                                            });

但它返回null。为什么呢?

public void AddUserWithProperdata_UserIsAddedAndEmailIsGenerated()
        {
            // Arrange
            String userName = "user";
            String firstName = "Ala";
            String secondName = "ADsadas";
            String passwd = "passwd";
            String email = "kot@wp.pl";
            DateTime birthdate = DateTime.Today;

            fakeUserService = A.Fake<IMwbeUserService>();
            fakeAuthenticationService = A.Fake<IAuthenticationService>();

            A.CallTo(() => fakeUserService
                .AddUser(new MwbeUserRegistrationIn() { UserName = userName, FirstName = firstName, SecondName = secondName, Password = passwd, Email = email, BirthDate = birthdate }))
              .Returns(new MwbeUser { UserName = userName, Email = email, FirstName = firstName, SecondName = secondName, BirthDate = birthdate });

            MwbeUsersController controller = new MwbeUsersController(fakeUserService, fakeAuthenticationService);

            MwbeUserRegistrationJson userjson = new MwbeUserRegistrationJson
            {
                username = userName,
                passwd = passwd,
                firstname = firstName,
                secondname = secondName,
                email = email,
                birthdate = birthdate
            };

            // Act
            IHttpActionResult untypedResult = controller.AddUser(userjson);
            var test1 = untypedResult as OkResult;
            var test2 = untypedResult as CreatedNegotiatedContentResult<MwbeUser>;

            // Assert
            Assert.IsNotNull(untypedResult);
        }



  public interface IMwbeUserService
        {
            MwbeUser AddUser(MwbeUserRegistrationIn regData);
...
}

更新1:添加了控制器代码

[RoutePrefix("users")]
    public class MwbeUsersController : ApiController
    {
        IMwbeUserService userSrv;
        IAuthenticationService authService;


        public MwbeUsersController(IMwbeUserService service, IAuthenticationService authSrv)
        {
            this.userSrv = service;
            this.authService = authSrv;
        }

...

     [Route("register")]
            [HttpPost]
            public IHttpActionResult AddUser(MwbeUserRegistrationJson userdatadto)
            {
                // Validation
                if (null == userdatadto)
                {
                    return BadRequest("No user data");
                }

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var registrationData = Conversion.ToUser(userdatadto);
                if(registrationData.Code != MwbeResponseCodes.OK)
                {
                    return BadRequest(registrationData.ErrorMessage);
                }

                // Registration
                try
                {
                    MwbeUser createdUser = userSrv.AddUser(registrationData.Data);
                    return Created<MwbeUser>("/users/" + createdUser.Id, createdUser); 
                }
                catch (UserAlreadyExistsException)
                {
                    return BadRequest("User with this username already exists");
                }
                catch (InvalidEmailAddress)
                {
                    return BadRequest("Given e-mail address is invalid");
                }

            }

1 个答案:

答案 0 :(得分:4)

我对FakeItEasy没什么经验,但我的猜测是你的期望太严格了。

AddUser的期望仅在使用被认为相等的对象调用时才匹配(就像使用object.Equals(object, object)一样。

由于您的控制器传入了另一个MwbeUserRegistrationIn对象(registrationData):

.AddUser(new MwbeUserRegistrationIn() {
    UserName = userName,
    FirstName = firstName,
    SecondName = secondName,
    Password = passwd,
    Email = email,
    BirthDate = birthdate }))

和MwbeUserRegistrationIn可能不会覆盖object.Equals(object),因此不会触发此期望。您可以使用基于值的语义实现MwbeUserRegistrationIn.Equals(object),也可以通过名为argument constraints的内容放宽您的期望。

在你的情况下,你可以稍微改写一下期望:

A.CallTo(() => fakeUserService.AddUser(A<MwbeUserRegistrationIn>.That.Matches(u =>
    u.UserName == userName &&
    u.FirstName == firstName &&
    u.SecondName == secondName &&
    u.Password == passwd &&
    u.Email == email &&
    u.BirthDate == birthdate)))
    .Returns(new MwbeUser
    {
        UserName = userName,
        Email = email,
        FirstName = firstName,
        SecondName = secondName,
        BirthDate = birthdate
    });