How to execute a DoInstead or Returns with out parameters

3 posts, 0 answers
  1. Nacho
    Nacho avatar
    15 posts
    Member since:
    Oct 2013

    Posted 04 Apr 2014 Link to this post

    Hello,

    I'm trying to do the following:

    [TestClass]
    public class JustMockTest
    {
        [TestMethod]
        public void TestMethod()
        {
            Mock.SetupStatic(typeof(Real));
     
            IntPtr test;
             Mock.Arrange(() => Real.RealMethod(Arg.IsAny<int>(), out test)).IgnoreArguments().Returns((int a, IntPtr b) => Fake.FakeMethod(a, out b));
     
            IntPtr expected;
            int result = Real.RealMethod(1, out expected);
        }
    }
     
    public static class Real
    {
        public static int RealMethod(int a, out IntPtr b)
        {
            b = new IntPtr(222);
     
            return a*2;
        }
    }
     
    public static class Fake
    {
        public static int FakeMethod(int a, out IntPtr b)
        {
            b = new IntPtr(111);
     
            return a * 4;
        }
    }

    The problem is that b is always empty. How can I get the value? I've checking the ​Arg.OutRefResult class but the documentation does not say anything about it.

    Thanks.
  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 09 Apr 2014 Link to this post

    Hello Nacho,

    Thank you for contacting us.

    To achieve this, you will have to use a delegate in the Returns function. Like this:
    public delegate int OutAction(int arg1, out IntPtr arg2);
     
    [TestMethod]
    public void TestMethod()
    {
        IntPtr test;
        Mock.Arrange(() => Real.RealMethod(Arg.IsAny<int>(), out test))
            .Returns(new OutAction((int a, out IntPtr b) => Fake.FakeMethod(a, out b)));
     
        IntPtr expected;
        int result = Real.RealMethod(1, out expected);
     
        Assert.AreEqual(4, result);
        Assert.AreEqual(111, expected.ToInt32());
    }

    As you can see, I also added assertion at the end of the test in order to check if everything is correct.

    I hope this helps.

    Regards,
    Kaloyan
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  3. DevCraft R3 2016 release webinar banner
  4. Nacho
    Nacho avatar
    15 posts
    Member since:
    Oct 2013

    Posted 10 Apr 2014 in reply to Kaloyan Link to this post

    Thanks for your help, it worked.
Back to Top