JMock,得到错误

时间:2013-10-09 07:52:44

标签: java jmock

获取错误:java.lang.AssertionError:意外调用:user.setUserName(“John”) 没有指定的期望:你......   - 忘记用基数条款开始期待?   - 调用模拟方法来指定期望的参数? 之前发生了什么:什么都没有!     在org.jmock.api.ExpectationError.unexpected(ExpectationError.java:23)

代码:

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 个答案:

答案 0 :(得分:0)

设置期望时,您可以通过调用of()调用返回的对象上的方法来指定您想要模拟的方法,而不是模拟本身(这不是&t; 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();
}