如何在JMockit中定义和扩展期望?

问题描述 投票:0回答:2

我最近开始使用JMockit。到目前为止它非常好。但我发现自己一遍又一遍地写这样的东西。

@Test
public void testFoo() {
    new Expectations() {
        x.foo(); result = "1";   // expectation common to all test cases
        x.bar(); result = "2";   // varying expectation per each case
    }
    ...
}

有没有办法定义一个常见的Expectations类,但是从每个测试用例扩展/覆盖它?

感谢你的帮助!

java unit-testing jmockit
2个回答
0
投票

我有时会这样做:

protected void prepareHttpClientExpectations(@Mocked final Call call, @Mocked final Response response,
                                                 @Mocked final ResponseBody responseBody,
                                                 final String requestMethod, final boolean isSuccessfull,
                                                 final String body) throws IOException {
        new Expectations() {{
            OkHttpClient client = new OkHttpClient();
            client.newCall(with(new Delegate<Request>() {
                boolean delegate(Request request) {
                    assertHttpRequest(request, requestMethod);
                    return true;
                }
            }));
            result = call;
            call.execute();
            result = response;
            response.isSuccessful();
            result = isSuccessfull;
            response.body();
            result = responseBody;
            responseBody.string();
            result = body;
        }};
    }

为了重用期望。然后你只需要调用具有所需值的方法并准备好;)


0
投票

您可以创建非最终期望并扩展它们。

doc

我们还可以创建命名子类,以便在多个测试中重用,而不是创建匿名子类。一些例子:

最终期望:

public final class MyReusableExpectations extends Expectations {    
    public MyReusableExpectations(...any parameters...) {       
        // expectations recorded here    
    } 
} 

非最终期望(可以作为基类扩展):

public class ReusableBaseExpectations extends Expectations {
    protected ReusableBaseExpectations(...) {
        // expectations here
    }
}

测试方法:

@Test 
public void someTest(@Mocked final SomeType aMock, etc.) {

    // Record reusable expectations by instantiating a final "...Expectations" class.
    new MyReusableExpectations(123, "test", etc.);

    // Record and extend reusable expectations by instantiating a non-final base class.
    new ReusableBaseExpectations() {{
        // additional expectations
    }};
}
© www.soinside.com 2019 - 2024. All rights reserved.