0

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");
    ;*/
}
4

1 回答 1

0

设置期望时,您可以通过在调用返回的对象上调用该方法来指定要模拟的方法of(),而不是在模拟本身上(这不是 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();
}
于 2013-11-07T07:23:07.207 回答