简体   繁体   中英

Can I pass property from Setup method to Return method while mocking an extending method using Moq

Consider the following class:

public interface IA{
    int C { get; set;}
    object Dummy(int A, int B);
}

public class A : IA
{
    public int C {get; set;}
    
    public object Dummy(int A, int B)
    {   
        return new { A,B,C};
    }
}

I do not understand how to moq such that the property is included in the returned object:

Mock<IA> mockedObject = new Mock<IA>();
mockedObject.SetUp(x => x.Dummy(It.IsAny<int>(),It.IsAny<int()).Returns((int A, int B) => { return new { A, B };// How do I return C along with A and B

I'm not even sure if it's possible, if it's not how should I be proceeding with such scenerio's?

I guess what you are looking for is something like:

using Moq;
using NUnit.Framework;

namespace TestUnitTests
{
    public interface IA
    {
        int C { get; set; }

        object Dummy(int A, int B);
    }

    public class A : IA
    {
        public int C { get; set; }

        public object Dummy(int A, int B)
        {
            return new { A, B, C };
        }
    }

    [TestFixture]
    public class TestClass
    {
        private Mock<IA> _mockedObject;

        [SetUp]
        public void Setup()
        {
            _mockedObject = new Mock<IA>();
        }

        [Test]
        public void Test()
        {
            const int A = 1;
            const int B = 2;
            const int C = 42;
            _mockedObject.SetupGet(m => m.C).Returns(C);
            ConfigureDummy(A, B);

            var dummy = _mockedObject.Object.Dummy(A, B);

            var expected = new { A, B, C };
            Assert.That(dummy.ToString(), Is.EqualTo(expected.ToString()));
        }

        private void ConfigureDummy(int A, int B)
        {
            _mockedObject
                .Setup(m => m.Dummy(A, B))
                .Returns(new { A, B, _mockedObject.Object.C });
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM