JMockIt Mocked Method not Mocking
<p>[10/7/06 4:00 Edited example code]
I'm trying to test some code (using JMockIt with TestNG) without touching the database, but it appears a mocked method is still actually called.  Here's the simplified setup:</p>

<pre><code>class DBRow {
    public DBRow() { }
    public DBRow(Object obj) {
        initialize(obj);
    }
    public void insert() {
        actuallyAddRowToDatabase();
    }
}

class MyObject extends DBRow {
    MyObject(Object obj) {
        super(obj);
    }
    public void insert(Object obj) {
        doSomething(obj);
        insert();
    }
}

class Factory {
    static MyObject createObject(Object obj1, Object obj2) {
        MyObject newObj = new MyObject(obj1);
        newObj.insert(obj2);
        return newObj;
    }
}
</code></pre>

<p>I wanted to mock the insert operation to prevent an insertion in the actual database, so I tried something like this:</p>

<pre><code>@Test
public void testCreation() {
    new Expectations(MyObject.class) {
        MyObject mock = new MyObject(null) {
            @Mock
            public void insert(Object obj) { }
        };
    {
        new MyObject(anyString);   result = mock;
    }};

    MyObject test = Factory.createObject("something", "something else");
}
</code></pre>

<p>But it appears that the real <code>insert(Object)</code> is still being called.  I'm specifying that the class is mocked so all instances should be mocked, right?  And I'm specifying that the insert method should be mocked, so why would the real method be getting called?</p>

<p>There's also a second problem with the above.  When I define the mock class inside the Expectations block (as above), it seems that only the <code>Row()</code> constructor is being called instead of <code>Row(Object)</code>, and thus the object is not correctly initialized.  I fixed this by moving it into a <code>@BeforeTest</code> method and instantiating the class there.  Here's what that looks like:</p>

<pre><code>private MyObject mock;

@BeforeTest
public void beforeTest() {
    new MockUp&lt;MyObject&gt;() {
        @Mock
        public void insert(Object obj) { }
    };
    mock = new MyObject("something");
}

@Test
public void testCreation() {
    new Expectations(MyObject.class) {{
        new MyObject(anyString);   result = mock;
    }};

    MyObject test = Factory.createObject("something", "something else");
}
</code></pre>

<p>So this seems to get the correct constructor to be called, but it still seems that <code>insert()</code> is being called as well.  Any insights?  </p>