Download private static field with JMockit?

I have a class, for example:

class ClassA { private static File myDir; // myDir is created at some stage private static String findFile(final String fileName) { for (final String actualBackupFileName : myDir.list()) { if (actualBackupFileName.startsWith(removeExtensionFrom(backupFile))) { return actualBackupFileName; } } } } 

So basically, I want to test this class by mocking the File class so that when I call list () it will return a list of strings that I define in my test class.

I have the following, but it doesn’t work at the moment, maybe something obvious that I am doing wrong - I am new to JMockit - any help is greatly appreciated!

 @Mocked("list") File myDir; @Test public void testClassA() { final String[] files = {"file1-bla.txt"}; new NonStrictExpectations() {{ new File(anyString).list(); returns(files); }}; String returnedFileName = Deencapsulation.invoke(ClassA.class, "findFile","file1.txt"); // assert returnedFileName is equal to "file1-bla.txt" } 

When performing the above test, I get a NullPointerException for the myDir field in ClassA - so it looks like it is being mocked incorrectly?

+6
source share
3 answers

JMockit (or any other mocking tool) does not mimic fields or variables; it mocks types (classes, interfaces, etc.). If instances of these types are stored inside the test code, it does not matter.

Test example 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. In addition, it is better to avoid bullying the File class. Instead, test only your public methods and use actual files instead of taunting the file system.

+10
source

You can use the setField method from the Deencapsulation class. Example below:

 Deencapsulation.setField(ClassA, "File", your_desired_value); 
+7
source

try the following:

 new Expectations {{ invoke(File.class, "list", null, null); returns(files); }} 
0
source

Source: https://habr.com/ru/post/949557/


All Articles