是否可以从NSubstitute的替代品中返回替代品?

时间:2014-08-22 13:31:50

标签: nsubstitute

interface IA {
   B Foo();
}


interface IB {
   // more code
}

var a = Substitute.For<IA>();
var b = Substitute.For<IB>();

a.Foo().Returns(b);

这可能吗?

1 个答案:

答案 0 :(得分:1)

假设您的界面IA意图有IB Foo();而非B Foo();,是的,这是可能的。请参阅以下示例,该示例使用NUnit。

namespace NSubstituteTests
{
    using NSubstitute;

    using NUnit.Framework;

    /// <summary>
    /// Corresponds to your type IA
    /// </summary>
    public interface IMyInterface
    {
        IMyOtherInterface Foo();
    }

    /// <summary>
    /// Corresponds to your type IB
    /// </summary>
    public interface IMyOtherInterface
    {
        string Message { get; }
    }

    [TestFixture]
    public class NSubstituteTest
    {
        [TestCase]
        public void TestSomething()
        {
            // var a = Substitute.For<IA>();
            var myConcreteClass = Substitute.For<IMyInterface>();

            // var b = Substitute.For<IB>();
            var myOtherConcreteClass = Substitute.For<IMyOtherInterface>();

            // a.Foo().Returns(b);
            myConcreteClass.Foo().Returns(myOtherConcreteClass);

            myOtherConcreteClass.Message.Returns("Thanks for testing!");

            var testResult = myConcreteClass.Foo().Message;
            Assert.AreEqual("Thanks for testing!", testResult);
        }
    }
}