本文介绍了如何更改 Moq 中的输入参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑

var list = new List<string>();
someObject.AddOne(list);
Assert.AreEqual(1, list.Count);

如何设置我的模拟?我期待

How can I setup my mock? I expect

var mock = new Mock<SomeObject>();
var list = new List<string>();
mock
    .Setup(so => so.AddOne(list))
    .Callback<List<string>>(l => l.Add("derp"));

工作,但没有调用回调.

to work, but the callback does not get called.

我无法更改 SomeObject,因为这是我使用的外部 API.

I cannot change SomeObject, since this is an external API I use.

推荐答案

此测试将成功:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;

namespace UnitTestProject
{
    [TestClass]
    public class UnitTest
    {
        public class SomeObject
        {
            public virtual void AddOne(List<string> aList) { }
        }

        [TestMethod]
        public void SomeTest()
        {
            // Arrange
            var mock = new Mock<SomeObject>();

            mock.Setup(so => so.AddOne(It.IsAny<List<string>>()))
                .Callback<List<string>>(l => l.Add("derp"));

            var target = mock.Object;
            var list = new List<string>();

            // Act
            target.AddOne(list);

            // Assert
            Assert.IsTrue(list.Contains("derp"));            
        }
    }
}

这篇关于如何更改 Moq 中的输入参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:32