0

I have a method that does something like this:

public void registerNewFoo( String someId )
{
    Foo foo = m_fooList.getFoo( someId );
    if ( foo != null )
    {
        // do something
        return;
    }

    // create new foo
    foo = new Foo();

    m_fooList.addNewFoo( foo );
}

And my test goes like this:

@Test
public void registerNewFoo_fooAddedToList( @Mocked final Foo mockFoo )
{
    new Expectations()
    {{
        m_mockFooList.getFoo( "test id" );
        result = null;

        new Foo();
        result = mockFoo;

        m_mockFooList.addNewFoo( mockFoo );
    }};

    Bar bar = new Bar( m_mockFooList );
    bar.registerNewFoo( "test id" );
}

Running the test gives me this error:

mockit.internal.UnexpectedInvocation: Parameter 0 of addNewFoo(Foo) expected Foo@1a679b7, got Foo@337d0f

If I change the addNewFoo expectation to this:

m_mockFooList.addNewFoo( (Foo)any );

then the test works fine.

The documentation says:

"By default, the exact instance on which instance method invocations will occur is not verified to be the same as the instance used when recording the expectation. That said, instance-specific matching can be obtained by annotating the mock field/parameter as @Injectable, or by using the onInstance(Object) method."

But I am not using @Injectable or onInstance(Object). Am I missing something else?

Using JMockit v1.7 and JUnit v4.8.1.

Kevin
  • 702
  • 7
  • 22
  • Note the error message refers to a *parameter* of the mocked method, while the documentation talks about the mocked instance *on which* the mocked method is called, ie, `m_mockFooList`. – Rogério Jun 16 '14 at 19:25

1 Answers1

1

The test is complicating things unnecessarily. Try the following instead:

@Test
public void registerNewFoo_fooAddedToList()
{
    Bar bar = new Bar(m_mockFooList);
    bar.registerNewFoo("test id");

    new Verifications() {{ m_mockFooList.addNewFoo((Foo) withNotNull()); }};
}

Note: m_mockFooList.getFoo(...) returns null by default if no expectations are recorded on it.

Rogério
  • 16,171
  • 2
  • 50
  • 63