如何在Moq中更改输入参数?

时间:2016-07-01 13:53:19

标签: c# moq

考虑

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

如何设置我的模拟?我希望

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

工作,但回调不会被调用。

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

1 个答案:

答案 0 :(得分:4)

此测试将成功:

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