Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change input parameter in Moq?

Tags:

c#

moq

Consider

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.

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

like image 419
Ruudjah Avatar asked Jul 01 '16 13:07

Ruudjah


1 Answers

This test will succeed:

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"));            
        }
    }
}
like image 144
Jeroen Heier Avatar answered Oct 19 '22 18:10

Jeroen Heier