Search code examples
javapass-by-referencejmockit

JMockit and pass-by-reference. One of us must be wrong (and it's probably me!)


I would be very grateful if someone could help me break through this issue I've been battling with recently. I am trying to mock a method that takes a double and a Calendar, and returns an integer that is determined by the value of the Calendar. The mock definition is below:

new NonStrictExpectations()
    {
        // this is my class to be mocked
        Calculator growthCalc;
        {
            GregorianCalendar month = new GregorianCalendar(2010, 0, 1);

            for (int i = 0; i < 3; i++)
            {
                // mock the "applyInflation" method
                growthCalc.applyInflation(anyDouble, month);
                result = i;

                month = (GregorianCalendar) month.clone();  //AAA
                month.add(Calendar.MONTH, 1);
            }

            growthCalc.toString();
            result = "Mocked Calculator";
        }
    };

The mock is set-up (calling toString() returns the correct text), but the applyInflation method returns zero for everything other than the last iteration of the loop above (i.e. it returns 2 when you pass-in the month new GregorianCalendar(2010,2,1).

I have concluded that the line marked AAA isn't having the effect I think it should. It doesn't seem to be changing the pointer to point to a new copy of "month" that I can modify without impacting the contents of the "month" that the mock expectation has set. Either that, or JMockit isn't recording the mock the way I thought.

Please help! Please tell me where I'm going wrong. I would really like to know what's up here as either my understanding of Java is fundamentally flawed or the JMockit implementation doesn't behave the way it "should" (according to me :) ). Or I've made a real schoolboy error that two evenings of starting haven't spotted...

Thank you.


Solution

  • Your test is perfectly correct. It only fails because of a bug in JMockit, which I am fixing right away. Sorry for the trouble!