background

Telerik JustMock

Mock Ref Return Values and Ref Locals

  • JustMock’s powerful capabilities enable you to mock methods with ref return references in order to test your code in perfect isolation.
  • Part of the fastest, most flexible and complete mocking tool for crafting unit tests.
  • Our award-winning support team is available to assist you with any issues.
Mock everything
  • Mocking Ref Return Values and Ref Locals Overview

     A reference return value means that a method returns a reference (or an alias) to some variable. That variable's scope must include the method. The variable's lifetime must extend beyond the return of the method. Modifications to the method's return value by the caller are made to the variable that is returned by the method.

    JustMock’s powerful capabilities enable you to mock methods with ref return references in order to test your code in perfect isolation.

    public class ClassUsingRefReturns
    {
        private static int[] array = { 1, 2, 3, 4 };
      
        public ref int GetRefReturnInstanceWithArgs(ref int p)
        {
            ref int local = ref array[0];
            local += p;
      
            return ref local;
        }
    }
     
    ...
     
    [TestMethod]
    public void MockRefReturnInstanceMethodWithArgs()
    {
        var localRef = LocalRef.WithValue(12);
      
        // Arrange
        var sut = Mock.Create<ClassUsingRefReturns>();
        Mock.Arrange(sut, s => s.GetRefReturnInstanceWithArgs(ref Arg.Ref(Arg.AnyInt).Value)))
            .Returns(localRef.Handle)
            .OccursOnce();
      
        // Act
        int param = 10;
        ref int res = ref sut.GetRefReturnInstance(ref param);
      
        // Assert
        Mock.Assert(sut);
        Assert.AreEqual(localRef.Ref, res);
    }

    Mock Ref Returns documentation
Next Steps