chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hi,

I've got the following bit of code. Where assign does not work

namespace UnitTests
{

    public static class MyClass
    {
        public static void Method(String param)
        {
            param = "not set";
        }
    }

    public class Caller
    {

        public void Call()
        {
            String b = "bye";

            MyClass.Method(b);
        }

    }

    [TestFixture]
    public class tests
    {
        [Test]
        public void test()
        {
            Mock myMock = MockManager.Mock(typeof(MyClass), Constructor.StaticNotMocked);
            myMock.ExpectCall("Method").Args(new Assign("hello"));

            Caller a = new Caller();
            a.Call();
        }
    }
}



If I make the parameter param explicitly a ref then it works. Eg. When the code is

namespace UnitTests
{

    public static class MyClass
    {
        public static void Method(ref String param)
        {
            param = "not set";
        }
    }

    public class Caller
    {

        public void Call()
        {
            String b = "bye";

            MyClass.Method(ref b);
        }

    }

    [TestFixture]
    public class tests
    {
        [Test]
        public void test()
        {
            Mock myMock = MockManager.Mock(typeof(MyClass), Constructor.StaticNotMocked);
            myMock.ExpectCall("Method").Args(new Assign("hello"));

            Caller a = new Caller();
            a.Call();
        }
    }
}


Anyone know why you have to explicitly set ref on the parameters if using assign, as I thought that all reference objects should be passed as reference anyway?
asked by niallmc (640 points)

1 Answer

0 votes
Hi,
ref is different then without ref.
here is an example:
public void WithRef(ref int a)
{
   a = 5;
}

public void WithoutRef(int a)
{
   a = 5;
}

public void Test()
{
   int i = 2;
   WithoutRef(i);
   Console.WriteLine(i);  // will print 2

   WithRef(ref i);
   Console.WriteLine(i);  // will print 5 (i changed)
}


This will print:
2
5

In any case Assign will work with normal arguments, (although you do need a license for that).

public static void WithoutRef(int a)
{
   Console.WriteLine(a); // a was assigned 10 although 0 was passed
}

[VerifyMocks]
[Test]
public void Test()
{
   Mock myMock = MockManager.Mock<MyClass>();
   myMock.ExpectUnmockedCall("WithoutRef").Args(new Assign(10)); 

   MyClass.WithoutRef(0);
}


This will print 10 because 'a' was assigned 10 when entering the mocked method
answered by scott (32k points)
...