Question

I have the following method....

public void testa(Car car) {
   em.persist(car);
   car.setEngine(null);

}

in my test i have:

protected final Car mockCar = context.mock(Car.class);

@Test
public void testCar() {
        context.checking(new Expectations() {
            {
                oneOf(em).persist(car);
                oneOf(car).setEngine(null);

                   }
             });
        this.stacker.testa(mockCar);
        context.assertIsSatisfied(); 

}

I run this and i keep getting :

unexpected invocation car.setEngine(null)...

If i remove the code that sets the engine in the code and from the test the tests passes... im totally confused as to why this is happening...

exception:

java.lang.AssertionError: unexpected invocation: car.setEngine(null) no expectations specified: did you... - forget to start an expectation with a cardinality clause? - call a mocked method to specify the parameter of an expectation?

Was it helpful?

Solution

Your problem appears to be that you have two Car objects. You have a car, which you set the expectations on, and a mockCar, which you pass through. Without seeing the definitions of these objects, I can't say for sure, but this is probably the root of your problem.

If this isn't the issue, we're going to need more code. Preferably the entire file(s).

For reference, this compiles fine and passes the tests:

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;

public class TestyMcTestTest {
    private final Mockery context = new Mockery();

    private final EntityManager em = context.mock(EntityManager.class);
    private final Stacker stacker = new Stacker(em);
    private final Car mockCar = context.mock(Car.class);

    @Test
    public void testCar() {
        context.checking(new Expectations() {{
            oneOf(em).persist(mockCar);
            oneOf(mockCar).setEngine(null);
        }});
        this.stacker.testa(mockCar);
        context.assertIsSatisfied();
    }

    public interface Car {
        void setEngine(Engine engine);
    }

    public interface Engine { }

    public class Stacker {
        private final EntityManager em;

        public Stacker(EntityManager em) {
            this.em = em;
        }

        public void testa(Car car) {
           em.persist(car);
           car.setEngine(null);
        }
    }

    private interface EntityManager {
        void persist(Object o);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top