FakeItEasy:模拟方法未返回预期结果 [英] FakeItEasy: mocked method is not returning expected result

查看:94
本文介绍了FakeItEasy:模拟方法未返回预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单元测试中使用FakeItEasy作为模拟框架.模拟方法fakeUserService.AddUser以返回新的MwbeUser对象,该对象在方法AddUser

Im using FakeItEasy as mocking framework in my unit tests. Method fakeUserService.AddUser is mocked to returned new MwbeUser object with some non-empty values inside method 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 
                                                            });

,但它返回空值.为什么?

but it returns nulls. Why?

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:添加了控制器代码

UPDATE 1: added code of controller

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

            }

推荐答案

我对FakeItEasy的经验很少,但是我的猜测是您的期望太严格了.

I have little experience with FakeItEasy, but my guess is that your expectation is too strict.

仅当使用被认为相等的对象调用AddUser时,期望值才匹配(就像使用

The expectation on AddUser will only match if it is called with an object that is considered equal (as if by using object.Equals(object, object).

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

Since your controller passes in a different MwbeUserRegistrationIn object (registrationData):

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

和MwbeUserRegistrationIn可能不会覆盖object.Equals(object),因此不会触发此期望.您可以使用基于值的语义来实现MwbeUserRegistrationIn.Equals(object),也可以通过参数约束.

and MwbeUserRegistrationIn presumably does not override object.Equals(object), this expectation will not be triggered. You can either implement MwbeUserRegistrationIn.Equals(object) with value-based semantics or relax your expectations by something called argument constraints.

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

In your case, you could rewrite the expectation a bit:

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

这篇关于FakeItEasy:模拟方法未返回预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆