模拟一个更新方法,用Moq返回空值 [英] Mock an update method returning a void with Moq

查看:78
本文介绍了模拟一个更新方法,用Moq返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试中,我将包含一些记录的List<IUser>定义为数据.

In my test, I defined as data a List<IUser> with some record in.

我想为方法Update设置最小量,该方法接收用户idstring进行更新.

I'd like setup a moq the methode Update, this method receive the user id and the string to update.

然后我得到IUser并更新属性LastName

Then I get the the IUser and update the property LastName

我尝试过这个:

namespace Tests.UnitTests
{
    [TestClass]
    public class UsersTest
    {
        public IUsers MockUsersRepo;
        readonly Mock<IUsers> _mockUserRepo = new Mock<IUsers>();
        private List<IUser> _users = new List<IUser>();

        [TestInitialize()]
        public void MyTestInitialize()
        {
            _users = new List<IUser>
                {
                    new User { Id = 1, Firsname = "A", Lastname = "AA", IsValid = true },
                    new User { Id = 1, Firsname = "B", Lastname = "BB", IsValid = true }
                };

            Mock<IAction> mockUserRepository = new Mock<IAction>();
            _mockUserRepo.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
                .Returns(???);

            MockUsersRepo = _mockUserRepo.Object;
        }

        [TestMethod]
        public void Update()
        {
            //Use the mock here
        }

    }
}

但是我收到此错误:无法解析返回符号

您有一个ID吗?

class User : IUser
{
    public int Id { get; set; }
    public string Firsname { get; set; }
    public string Lastname { get; set; }
    public bool IsValid { get; set; }
}

interface IUser
{
    int Id { get; set; }
    string Firsname { get; set; }
    string Lastname { get; set; }
    bool IsValid { get; set; }
}

interface IAction
{
    List<IUser> GetList(bool isActive);
    void Update(int id, string lastname)
}

class Action : IAction
{
    public IUser GetById(int id)
    {
        //....
    }
    public void Update(int id, string lastname)
    {
        var userToUpdate = GetById(id);
        userToUpdate.LastName = lastname;
        //....
    }
}

推荐答案

如果只想验证此方法是否被调用,则应使用Verifiable()方法.

If you just want to verify this method is called, you should use Verifiable() method.

_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
                   .Verifiable();

如果您还想对这些参数进行操作,请先使用Callback().

If you also want to do something with those parameters, use Callback() first.

_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
                   .Callback((int id, string lastName) => {
                       //do something
                       }).Verifiable();

更新

如果返回bool值作为结果,则应在此处进行模拟.

Here's how you should mock it if you return a bool value as result.

_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
                   .Returns(true);

这篇关于模拟一个更新方法,用Moq返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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