mock方法没有返回预期的结果

本文关键字:结果 返回 方法 mock | 更新日期: 2023-09-27 18:08:39

我在单元测试中使用FakeItEasy作为mock框架。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);
...
}

UPDATE 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");
                }
            }

mock方法没有返回预期的结果

我对FakeItEasy没有什么经验,但我猜您的期望太严格了。

对AddUser的期望只有在用一个被认为相等的对象调用时才会匹配(就像使用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),也可以通过所谓的参数约束来放松您的期望。

在您的情况下,您可以稍微重写一下期望:

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
    });