JUnit test notes I

  • Test method with parameter: @Mocked object

Learn how to recording expectations…, which needs further justification.

@Test
public void test_targetMethod(@Mocked final SomeObj someObj) throws Exception {
new Expectations() {{
final int A = 5;
someObj.getStringList((Integer) any);
result = new mockit.Delegate() {
ArrayList<String> getStirngList(int para) {
List<String> strList = new ArrayList<String>();
for(int i = 1; i <= 3; ++i){
strList.add(String.valueOf(A * i));
}
return strList;
}
};
}};

List<String> result = someClass.targetMethod();
assertNotNull(result);
assertEquals(3, result.size());
}

REMARK 1:
a) Define @Morked object as a member in class level
For example:

@Mocked 
private Object httpServiceImpl; //as a class member

Then, if we have result in the httpServiceImpl, it turns out that result is NULL.

b) Define as a parameter in method
For example:

public void testProcessDeposit_success(@Mocked final HttpServiceImpl httpServiceImpl){
}

Then, results in httpServiceImpl has real value.

REMARK 2:
a) In case of NonStrictExpectations. When calling the method, the order does not matter.

new NonStrictExpectations(){{
execute1();
execute2();
}};

b) In case of Expectations, the test must follow the order of steps exactly.

new Expectations() {{
//Step 1;
executeFirst();

//Step 2;
executeSecond();
}};

The test will fail if the executeSecond() is called before executeFirst().

  • Debug: “method should have no parameters”

Using Junit 4.8, Jmockit 1.8, Jmock 1.1 for unit test and facing the error: java.lang.Exception: Method testMethod should have no parameters when having test method as:

@Test
public void testMethod(@Mocked final Object obj) throws Exception {
}

Commonly, @Test method is not allowed to have parameters. But it’s not the case with Jmockit: “Jmockit getting started: recording expectations“.

Finally, the problem is solved by reordering the library in module config file for ItelliJ. In .iml file, the order of the the JMockit jar must appear before JUnit. For example,

<orderEntry type="library" name="Maven: jmockit:1.8" level="project" />
<orderEntry type="library" name="Maven: jmock:1.1.0" level="project" />
<orderEntry type="library" name="Maven: junit:4.8.1" level="project" />