0
votes

Getting error : java.lang.AssertionError: unexpected invocation: user.setUserName("John") 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? what happened before this: nothing! at org.jmock.api.ExpectationError.unexpected(ExpectationError.java:23)

Code:

Mockery context = new JUnit4Mockery();

@Test
public void testSayHello(){
    context.setImposteriser(ClassImposteriser.INSTANCE);
    final User user =  context.mock(User.class);
//  user.setUserName("John");
    context.checking(new Expectations(){{
        exactly(1).of(user);
        user.setUserName("John");
        will(returnValue("Hello! John"));
    }}
    );
     context.assertIsSatisfied();
    /*HelloWorld helloWorld = new HelloWorld();
    Assert.assertEquals(helloWorld.sayHelloToUser(user), "Hello! John");
    ;*/
}
1

1 Answers

0
votes

When setting up expectations, you specify the method you'd like to mock by calling that method on the object returned by your call to of(), not on the mock itself (this isn't EasyMock).

@Test
public void testSayHello(){
    // setting up the mock
    context.setImposteriser(ClassImposteriser.INSTANCE);
    final User user =  context.mock(User.class);
    context.checking(new Expectations(){{
        exactly(1).of(user).setUserName("John");
        will(returnValue("Hello! John"));
    }});

    // using the mock
    HelloWorld helloWorld = new HelloWorld();
    String greeting = helloWorld.sayHelloToUser(user);

    // checking things afterward
    Assert.assertEquals(greeting, "Hello! John");
    context.assertIsSatisfied();
}