JMockit (or any other mocking tool) does not mock fields or variables, it mocks types (classes, interfaces, etc.) Where the instances of those types get stored inside the code under test is not relevant.
Example test for ClassA
:
@Test
public void testClassA(@Mocked File myDir)
{
new Expectations() {{ myDir.list(); result = "file1-bla.txt"; }};
String returnedFileName = new ClassA().publicMethodThatCallsFindFile("file1.txt");
assertEquals("file1-bla.txt", returnedFileName);
}
The above should work. Note that testing private
methods directly (or accessing private
fields) is considered bad practice, so I avoided it here. Also, it's best to avoid mocking the File
class. Instead, test only your public
methods, and use actual files instead of mocking the filesystem.