如何为起订量中的属性赋值?

How to assign values to properties in moq?(如何为起订量中的属性赋值?)
本文介绍了如何为起订量中的属性赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个类,其方法返回 User

I have a class with a method that returns an object of type User

public class CustomMembershipProvider : MembershipProvider
{
    public virtual User GetUser(string username, string password, string email, bool isApproved)
    {
        return new User()
            {
                Name = username
                ,Password = EncodePassword(password)
                ,Email = email
                ,Status = (isApproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente)
                // ...
            };
    }

    // ..
}

User 是一个域对象.注意带有 setter as protectedId 属性:

User is a domain object. Note the Id property with setter as protected:

public class User : IAuditable, IUser
{
    public virtual int Id { get; protected set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
    public virtual UsuarioStatusEnum Status { get; set; }
    public virtual string Password { get; set; }
}

Id 受到保护,因为它是由数据库生成的.

在我的测试项目中,我有一个带有 Store 方法的 Fake 存储库来保存/更新对象:

In my Test project I have a Fake repository with a method Store to save/update the object:

public void Store(T obj)
{
    if (obj.Id > 0)
        _context[obj.Id] = obj;
    else
    {
        var generateId =  _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
        var stubUser = Mock.Get<T>(obj); // In test, will always mock
        stubUser.Setup(s => s.Id).Returns(generateId);
        _context.Add(generateId, stubUser.Object);
    }
}

CustomMembershipProvider 我有 public override MembershipUser CreateUser 方法,该方法调用 GetUser 来创建 User.
这样,我所要做的就是模拟 GetUser 方法,以便存储库可以生成 Id

In CustomMembershipProvider I have public override MembershipUser CreateUser method that calls the GetUser to create a User.
This way, all I have to do is mock the GetUser method so that the repository can generate the Id

var membershipMoq = new Mock<CustomMembershipProvider>();
membershipMoq.CallBase = true;
membershipMoq
    .Setup(p => p.GetUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
    .Returns<string, string, string, bool>( (username, password, email, isAproved) => {
        var moqUser = new Mock<User>();
        moqUser.Object.Name = username;
        moqUser.Object.Password = password;
        moqUser.Object.Email = email;
        moqUser.Object.Status = (isAproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente);
        return moqUser.Object;
    });
_membershipProvider = membershipMoq.Object;

问题

理论上一切都是正确的.当CreateUser调用'GetUser'创建用户时,用户会返回Mockfilled;

Problem

In theory everything is correct. When CreateUser call 'GetUser' to create a user, the user will return Mock filled;

[TestMethod]
public void CreateUser_deve_criar_usuario_no_repositorio()
{
    // Act
    MembershipCreateStatus status;
    var  usr = _membershipProvider.CreateUser(
        _fixture.Create<string>(),
        _fixture.Create<string>(),
        _fixture.Create<string>(),
        null, null, true, null,
        out status);

    // usr should have name, email password filled. But not!

    // Assert
    status.Should().Be(MembershipCreateStatus.Success);
}

问题是邮箱、姓名、密码都是空的(有默认值)!

The problem is that Email, Name, Password are empty (with default values)!

推荐答案

你准备模拟用户的方式是个问题.

The way you prepare the mocked user is the problem.

moqUser.Object.Name = username;

不会设置名称,除非您已正确设置模拟.在给属性赋值之前试试这个:

will not set the name, unless you have setup the mock properly. Try this before assigning values to properties:

moqUser.SetupAllProperties();

此方法将准备模拟上的所有属性,以便能够记录分配的值,并在以后重播(即充当真实属性).

This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).

您还可以使用 SetupProperty() 方法来设置各个属性,以便能够记录传入的值.

You can also use SetupProperty() method to set up individual properties to be able to record the passed in value.

另一种方法是:

var mockUser = Mock.Of<User>( m =>
    m.Name == "whatever" &&
    m.Email == "someone@example.com"); 

return mockUser;

这篇关于如何为起订量中的属性赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)