【问题标题】:How to define and extends Expectations in JMockit?如何在 JMockit 中定义和扩展期望?
【发布时间】:2018-03-01 18:25:39
【问题描述】:

我最近开始使用 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


    【解决方案1】:

    我有时会这样做:

    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;
            }};
        }
    

    为了重用期望。然后,您只需要使用所需的值调用该方法并准备就绪;)

    【讨论】:

      【解决方案2】:

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

      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
          }};
      }
      

      【讨论】:

      • 谢谢,但您链接的文档与官方文档不同(我认为?)here。你链接的那个是最新的吗?
      • @DanielYoon 对不起,它是 1.16 版本。不是最新的。我想你可以试试看。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2023-01-04
      • 2016-08-27
      • 1970-01-01
      相关资源
      最近更新 更多