A Guide to JMockit Expectations – 对JMockit的期望指南

最后修改: 2016年 7月 21日

中文/混合/英文(键盘快捷键:t)

1. Intro

1.介绍

This article is the second installment in the JMockit series. You may want to read the first article as we are assuming that you are already familiar with JMockit’s basics.

本文是JMockit系列的第二篇文章。您可能希望阅读第一篇文章,因为我们假设您已经熟悉了JMockit的基础知识。

Today we’ll go deeper and focus on expectations. We will show how to define more specific or generic argument matching and more advanced ways of defining values.

今天我们将更深入地探讨,并关注期望。我们将展示如何定义更具体或通用的参数匹配和更高级的定义值的方法。

2. Argument Values Matching

2.参数值匹配

The following approaches apply both to Expectations as well as Verifications.

以下方法既适用于期望,也适用于验证

2.1. “Any” Fields

2.1.”任何 “字段

JMockit offers a set of utility fields for making argument matching more generic. One of these utilities are the anyX fields.

JMockit提供了一组实用字段,用于使参数匹配更加通用。其中一个实用工具是anyX字段。

These will check that any value was passed and there is one for each primitive type (and the corresponding wrapper class), one for strings, and a “universal” one of type Object.

这些将检查是否有任何值被传递,每个原始类型(和相应的封装类)都有一个,字符串有一个,还有一个Object类型的 “通用 “的。

Let’s see an example:

让我们看一个例子。

public interface ExpectationsCollaborator {
    String methodForAny1(String s, int i, Boolean b);
    void methodForAny2(Long l, List<String> lst);
}

@Test
public void test(@Mocked ExpectationsCollaborator mock) throws Exception {
    new Expectations() {{
        mock.methodForAny1(anyString, anyInt, anyBoolean); 
        result = "any";
    }};

    Assert.assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
    mock.methodForAny2(2L, new ArrayList<>());

    new FullVerifications() {{
        mock.methodForAny2(anyLong, (List<String>) any);
    }};
}

You must take into account that when using the any field, you need to cast it to the expected type. The complete list of fields is present in the documentation.

你必须考虑到,当使用any字段时,你需要将它投射到预期的类型。完整的字段列表存在于文档中。

2.2. “With” Methods

2.2.”有 “方法

JMockit also provides several methods to help with generic argument matching. Those are the withX methods.

JMockit还提供了几个方法来帮助进行通用参数匹配。这些是withX方法。

These allow for a little more advanced matching than the anyX fields. We can see an example here in which we’ll define an expectation for a method that will be triggered with a string containing foo, an integer not equal to 1, a non-null Boolean and any instance of the List class:

这些允许比anyX字段更高级的匹配。我们可以在这里看到一个例子,我们将为一个方法定义一个期望,该方法将在包含foo的字符串、不等于1的整数、非空的Boolean以及List类的任何实例时被触发。

public interface ExpectationsCollaborator {
    String methodForWith1(String s, int i);
    void methodForWith2(Boolean b, List<String> l);
}

@Test
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
    new Expectations() {{
        mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
        result = "with";
    }};

    assertEquals("with", mock.methodForWith1("barfooxyz", 2));
    mock.methodForWith2(Boolean.TRUE, new ArrayList<>());

    new Verifications() {{
        mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
    }};
}

You can see the complete list of withX methods on JMockit’s documentation.

您可以在JMockit的文档上看到withX方法的完整列表。

Take into account that the special with(Delegate) and withArgThat(Matcher) will be covered in their own subsection.

考虑到特殊的with(Delegate)withArgThat(Matcher)将在他们自己的小节中讲述。

2.3. Null Is Not Null

2.3.零不是零

Something that is good to understand sooner than later is that null is not used to define an argument for which null has been passed to a mock.

尽早了解的事情是,null不能用来定义一个null已经传递给mock的参数。

Actually, null is used as syntactic sugar to define that any object will be passed (so it can only be used for parameters of reference type). To specifically verify that a given parameter receives the null reference, the withNull() matcher can be used.

实际上,null是作为语法糖来定义任何对象将被传递(所以它只能用于引用类型的参数)。为了具体验证一个给定的参数是否收到null引用,可以使用withNull()匹配器。

For the next example, we’ll define the behaviour for a mock, that should be triggered when the arguments passed are: any string, any List, and a null reference:

在下一个例子中,我们将定义一个mock的行为,当传递的参数是:任何字符串、任何List和一个null引用时,应该被触发。

public interface ExpectationsCollaborator {
    String methodForNulls1(String s, List<String> l);
    void methodForNulls2(String s, List<String> l);
}

@Test
public void testWithNulls(@Mocked ExpectationsCollaborator mock){
    new Expectations() {{
        mock.methodForNulls1(anyString, null); 
        result = "null";
    }};
    
    assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
    mock.methodForNulls2("blablabla", null);
    
    new Verifications() {{
        mock.methodForNulls2(anyString, (List<String>) withNull());
    }};
}

Note the difference: null means any list and withNull() means a null reference to a list. In particular, this avoids the need to cast the value to the declared parameter type (see that the third argument had to be cast but not the second one).

注意其中的区别。null 表示任何列表,withNull() 表示对一个列表的null引用。特别是,这就避免了将数值转换为声明的参数类型的需要(请看,第三个参数必须被转换,但第二个参数不需要)。

The only condition to be able to use this is that at least one explicit argument matcher had been used for the expectation (either a with method or an any field).

能够使用这个的唯一条件是,至少有一个明确的参数匹配器被用于期望(要么是一个with方法,要么是一个any域)。

2.4. “Times” Field

2.4.”时代 “字段

Sometimes, we want to constrain the number of invocations expected for a mocked method. For this, JMockit has the reserved words times, minTimes and maxTimes (all three allow non-negative integers only).

有时,我们想约束被模拟方法的预期调用次数。为此,JMockit有保留词timesminTimesmaxTimes(这三个词都只允许非负整数)。

public interface ExpectationsCollaborator {
    void methodForTimes1();
    void methodForTimes2();
    void methodForTimes3();
}

@Test
public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
    new Expectations() {{
        mock.methodForTimes1(); times = 2;
        mock.methodForTimes2();
    }};
    
    mock.methodForTimes1();
    mock.methodForTimes1();
    mock.methodForTimes2();
    mock.methodForTimes3();
    mock.methodForTimes3();
    mock.methodForTimes3();
    
    new Verifications() {{
        mock.methodForTimes3(); minTimes = 1; maxTimes = 3;
    }};
}

In this example, we’ve defined that exactly two invocations (not one, not three, exactly two) of methodForTimes1() should be done using the line times = 2;.

在这个例子中,我们定义了对methodForTimes1()的两次调用(不是一次,不是三次,正好是两次),应该使用行times = 2;

Then we used the default behavior (if no repetition constraint is given minTimes = 1; is used) to define that at least one invocation will be done to methodForTimes2().

然后我们使用默认行为(如果没有给出重复约束,则使用minTimes = 1;)来定义至少要对methodForTimes2()进行一次调用。

Lastly, using minTimes = 1; followed by maxTimes = 3; we defined that between one and three invocations would occur to methodForTimes3().

最后,使用minTimes = 1;maxTimes = 3;,我们定义了对methodForTimes3()的调用将发生在1到3次之间。

Take into account that both minTimes and maxTimes can be specified for the same expectation, as long as minTimes is assigned first. On the other hand, times can only be used alone.

考虑到minTimesmaxTimes都可以为同一个期望值指定,只要minTimes被首先指定。另一方面,times只能单独使用。

2.5. Custom Argument Matching

2.5.自定义参数匹配

Sometimes argument matching is not as direct as simply specifying a value or using some of the predefined utilities (anyX or withX).

有时,参数匹配不像简单地指定一个值或使用一些预定义的工具(anyXwithX)那样直接。

For that cases, JMockit relies on Hamcrest‘s Matcher interface. You just need to define a matcher for the specific testing scenario and use that matcher with a withArgThat() call.

对于这种情况,JMockit依赖于HamcrestMatcher接口。你只需要为特定的测试场景定义一个匹配器,并通过withArgThat()调用来使用该匹配器。

Let’s see an example for matching a specific class to a passed object:

让我们看一个例子,将一个特定的类与一个传递的对象相匹配。

public interface ExpectationsCollaborator {
    void methodForArgThat(Object o);
}

public class Model {
    public String getInfo(){
        return "info";
    }
}

@Test
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
    new Expectations() {{
        mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
            @Override
            public boolean matches(Object item) {
                return item instanceof Model && "info".equals(((Model) item).getInfo());
            }

            @Override
            public void describeTo(Description description) { }
        }));
    }};
    mock.methodForArgThat(new Model());
}

3. Returning Values

3.返回值

Let’s now look at the return values; keep in mind that following approaches apply only to Expectations as no return values can be defined for Verifications.

现在我们来看看返回值;请记住,以下方法只适用于Expectations,因为不能为Verifications定义返回值。

3.1. Result and Returns (…)

3.1.结果和回报(…)

When using JMockit, you have three different ways of defining the expected result of the invocation of a mocked method. Of all three, we’ll talk now about the first two (the simplest ones) which will surely cover 90% of everyday use cases.

当使用JMockit时,你有三种不同的方式来定义调用被模拟方法的预期结果。在这三种方式中,我们现在将讨论前两种(最简单的),它们肯定会涵盖90%的日常使用情况。

These two are the result field and the returns(Object…) method:

这两个是result字段和returns(Object..)方法。

  • With the result field, you can define one return value for any non-void returning mocked method. This return value can also be an exception to be thrown (this time working for both non-void and void returning methods).
    • Several result field assignations can be done in order to return more than one value for more than one method invocations (you can mix both return values and errors to be thrown).
    • The same behaviour will be achieved when assigning to result a list or an array of values (of the same type than the return type of the mocked method, NO exceptions here).
  • The returns(Object…) method is syntactic sugar for returning several values of the same time.

This is more easily shown with a code snippet:

这一点用一个代码片断更容易显示。

public interface ExpectationsCollaborator{
    String methodReturnsString();
    int methodReturnsInt();
}

@Test
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
    new Expectations() {{
        mock.methodReturnsString();
        result = "foo";
        result = new Exception();
        result = "bar";
        returns("foo", "bar");
        mock.methodReturnsInt();
        result = new int[]{1, 2, 3};
        result = 1;
    }};

    assertEquals("Should return foo", "foo", mock.methodReturnsString());
    try {
        mock.methodReturnsString();
        fail("Shouldn't reach here");
    } catch (Exception e) {
        // NOOP
    }
    assertEquals("Should return bar", "bar", mock.methodReturnsString());
    assertEquals("Should return 1", 1, mock.methodReturnsInt());
    assertEquals("Should return 2", 2, mock.methodReturnsInt());
    assertEquals("Should return 3", 3, mock.methodReturnsInt());
    assertEquals("Should return foo", "foo", mock.methodReturnsString());
    assertEquals("Should return bar", "bar", mock.methodReturnsString());
    assertEquals("Should return 1", 1, mock.methodReturnsInt());
}

In this example, we have defined that for the first three calls to methodReturnsString() the expected returns are (in order) “foo”, an exception and “bar”. We achieved this using three different assignations to the result field.

在这个例子中,我们定义了对于前三次对methodReturnsString()的调用,预期的回报是(按顺序)“foo”、一个异常和“bar”。我们通过对result字段进行三种不同的赋值来实现这一点。

Then on line 14, we defined that for the fourth and fifth calls, “foo” and “bar” should be returned using the returns(Object…) method.

然后在第14行,我们定义对于第四和第五次调用,“foo”“bar”应该使用returns(Object…)方法返回。

For the methodReturnsInt() we defined on line 13 to return 1, 2 and lastly 3 by assigning an array with the different results to the result field and on line 15 we defined to return 1 by a simple assignation to the result field.

对于methodReturnsInt(),我们在第13行定义了返回1、2和最后的3,通过将不同结果的数组分配给result字段,在第15行我们定义了返回1,通过简单分配给result字段。

As you can see there are several ways of defining return values for mocked methods.

正如你所看到的,有几种方法来定义模拟方法的返回值。

3.2. Delegators

3.2. 代表

To end the article we’re going to cover the third way of defining the return value: the Delegate interface. This interface is used for defining more complex return values when defining mocked methods.

在文章的最后,我们将介绍定义返回值的第三种方式:Delegate接口。这个接口用于在定义模拟方法时定义更复杂的返回值。

We’re going to see an example to simply the explaining:

我们将看到一个例子来简单解释。

public interface ExpectationsCollaborator {
    int methodForDelegate(int i);
}

@Test
public void testDelegate(@Mocked ExpectationsCollaborator mock) {
    new Expectations() {{
        mock.methodForDelegate(anyInt);
            
        result = new Delegate() {
            int delegate(int i) throws Exception {
                if (i < 3) {
                    return 5;
                } else {
                    throw new Exception();
                }
            }
        };
    }};

    assertEquals("Should return 5", 5, mock.methodForDelegate(1));
    try {
        mock.methodForDelegate(3);
        fail("Shouldn't reach here");
    } catch (Exception e) {
    }
}

The way to use a delegator is to create a new instance for it and assign it to a returns field. In this new instance, you should create a new method with the same parameters and return type than the mocked method (you can use any name for it). Inside this new method, use whatever implementation you want in order to return the desired value.

使用委托者的方法是为其创建一个新的实例,并将其分配给returns字段。在这个新实例中,你应该创建一个新的方法,其参数和返回类型与被模拟的方法相同(你可以使用任何名字)。在这个新方法中,使用你想要的任何实现,以便返回你想要的值。

In the example, we did an implementation in which 5 should be returned when the value passed to the mocked method is less than 3 and an exception is thrown otherwise (note that we had to use times = 2; so that the second invocation is expected as we lost the default behaviour by defining a return value).

在这个例子中,我们做了一个实现,当传递给被模拟方法的值小于3时,应该返回5,否则会抛出一个异常(注意,我们必须使用times = 2;,以便第二次调用是预期的,因为我们通过定义一个返回值失去了默认行为)。

It may seem like quite a lot of code, but for some cases, it’ll be the only way to achieve the result we want.

这可能看起来是相当多的代码,但在某些情况下,这将是实现我们想要的结果的唯一途径。

4. Conclusion

4.结论

With this, we practically showed everything we need to create expectations and verifications for our everyday tests.

有了这个,我们实际上展示了我们为日常测试创建预期和验证所需的一切。

We’ll of course publish more articles on JMockit, so stay tuned to learn even more.

当然,我们会发表更多关于JMockit的文章,请继续关注,以了解更多。

And, as always, the full implementation of this tutorial can be found on the GitHub project.

而且,一如既往地,本教程的完整实现可以在GitHub项目上找到。

4.1. Articles in the Series

4.1.该系列的文章

All articles of the series:

该系列的所有文章。