使用 JMockit 模拟私有静态字段?

使用 JMockit 模拟私有静态字段?

问题描述:

我有一个类似下面的类;

I have a class like the following;

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;
            }
       }
    }
}

所以,基本上,我想通过模拟 File 类来测试这个类,以便在调用 list() 时它返回我在测试类中定义的字符串列表.

So, basically, I want to test this class by mocking out the File class so that when list() is called on it it returns a list of strings I define in my test class.

我有以下内容,但目前无法正常工作,可能有一些明显的我做错了 - 我是 JMockit 的新手 - 非常感谢任何帮助!

I've got the following but its not working at the minute, there's probably something obvious I'm doing wrong - I'm new to JMockit - any help is much 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"
  }

在运行上述测试时,我得到 ClassA 中 myDir 字段的 NullPointerException - 所以它看起来没有被正确模拟?

When running the above test I get a NullPointerException for the myDir field in ClassA - so it looks like its not getting mocked properly?

JMockit(或任何其他模拟工具)不模拟字段或变量,它模拟类型(类、接口等)这些类型的实例存储在被测代码中的位置无关.

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.

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);
}

以上应该可以工作.请注意,直接测试 private 方法(或访问 private 字段)被认为是不好的做法,所以我在这里避免了它.此外,最好避免模拟 File 类.相反,只测试您的 public 方法,并使用实际文件而不是模拟文件系统.

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.