With a very simple Mockito run JUnit test and class I am seeing different output when the test is run with Java 1.6.0_32 and Java 1.7.0_04 and want to understand why this is happening. I suspect there is some type erasure going on but would like a definitive answer.
Here is my example code and instructions on how to run from the command line:
FooServiceTest.java
import org.junit.*;
import org.junit.runner.*;
import org.mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
import java.util.*;
@RunWith(MockitoJUnitRunner.class)
public class FooServiceTest {
@Mock Map<String, String> mockStringString;
@Mock Map<String, Integer> mockStringInteger;
@InjectMocks FooService fooService;
public static void main(String[] args) {
new JUnitCore().run(FooServiceTest.class);
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void checkInjection() {
when(mockStringString.get("foo")).thenReturn("bar");
fooService.println();
}
}
FooService.java
import java.util.*;
public class FooService {
private Map<String, String> stringString = new HashMap<String, String>();
private Map<String, Integer> stringInteger = new HashMap<String, Integer>();
public void println() {
System.out.println(stringString.get("foo") + " " + stringInteger);
}
}
To compile and run this example:
- save the above into files
- download and put in the same directory junit.4.10.jar and mockito-all-1.9.0.jar
- set PATH to include a JDK
- compile with
javac -cp junit-4.10.jar;mockito-all-1.9.0.jar *.java
- run with
java -cp .;junit-4.10.jar;mockito-all-1.9.0.jar FooServiceTest
I believe the output from above is I null {}
because @InjectMocks field injection cannot correctly resolve the types since they are both of type Map. Is this correct?
Now changing one of the mock names to match the field in the class should allow Mockito to find a match. For example changing
@Mock Map<String, Integer> mockStringInteger;
to
@Mock Map<String, Integer> stringInteger;
then compiling/running with Java 1.6.0_32 gives (IMHO the expected) output bar stringInteger
but with 1.7.0_04 gives null stringInteger
.
Here is how I am running it (from a command line in Windows 7):
E:\src\mockito-test>set PATH="C:\Program Files (x86)\Java\jdk1.6.0_32\bin"
E:\src\mockito-test>javac -cp junit-4.10.jar;mockito-all-1.9.0.jar *.java
E:\src\mockito-test>java -cp .;junit-4.10.jar;mockito-all-1.9.0.jar FooServiceTest
bar stringInteger
E:\src\mockito-test>set PATH="C:\Program Files (x86)\Java\jdk1.7.0_04\bin"
E:\src\mockito-test>javac -cp junit-4.10.jar;mockito-all-1.9.0.jar *.java
E:\src\mockito-test>java -cp .;junit-4.10.jar;mockito-all-1.9.0.jar FooServiceTest
null stringInteger