简体   繁体   English

Mockito java - 模拟第三方实用方法和私有方法调用

[英]Mockito java - mock third party utility methods and private method calls

I have a legacy code which has some methods like below:我有一个遗留代码,它有如下一些方法:

public void display(String fileName, Path path){
    //do some stuff
    Files.exists(path);
    if(null==privateMethod(fileName))
       //something
}

private Object privateMethod(String fileName){
   // do something
   return object;
}

I am writing tests(using mockito) for display method.我正在为显示方法编写测试(使用 mockito)。 How do I get around calls like Files.exists(path) and internal private method calls because I think normal stubbing cannot used with private method(visibility issue).我如何绕过 Files.exists(path) 之类的调用和内部私有方法调用,因为我认为普通存根不能与私有方法一起使用(可见性问题)。 As Files.exists() is utility method so cannot be mocked.由于 Files.exists() 是实用方法,因此不能被模拟。 Do I need to actually create some test files in testing method and probably delete them?我是否需要在测试方法中实际创建一些测试文件并可能删除它们? Or is there a better clean way.或者有没有更好的清洁方法。 Also I have searched regarding private method testing - everyone suggests powermock which Iam not allowed to use.我还搜索了有关私有方法测试的信息-每个人都建议我不允许使用 powermock。 Anyway I don't need to test private method but bypass/stub their call returns.无论如何,我不需要测试私有方法,而是绕过/存根他们的调用返回。

In this case makes sense to have some files for testing.在这种情况下,有一些文件用于测试是有意义的。 You can generate them or create them in advance in the folder src/test/resources .您可以在文件夹src/test/resources中生成或提前创建它们。

For example a test might look like this:例如,测试可能如下所示:

@Test
public void myTest(){
    // MyFile.txt is in src/test/resources
    Path path = Paths.get("src","test","resources"); 
    service.display("MyFile.txt", path);
    // Asserts..
}

Regarding mocking private methods, in general is not recommended because your test will depend on implementation details of your class, so I strongly discourage it.关于 mocking 私有方法,一般不推荐,因为你的测试将取决于你的 class 的实现细节,所以我强烈反对。 Furthermore, if you are not allowed to use Powermock it might not be possible at all.此外,如果不允许您使用Powermock ,则可能根本不可能。

But there are alternatives, for example if the private method uses some external services or libraries, than you can mock them instead of the whole method.但是还有其他选择,例如,如果私有方法使用一些外部服务或库,那么您可以模拟它们而不是整个方法。 The idea is to mock the external entities that the class depends on rather than parts of the class itself.这个想法是模拟 class 所依赖的外部实体,而不是 class 本身的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM