对java模拟文件的建议(模拟java.io.File) [英] Suggestions for a java Mock File (to mock java.io.File)

查看:197
本文介绍了对java模拟文件的建议(模拟java.io.File)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有一个java模拟File对象的建议?
我正在使用需要获取java.io.File对象作为参数的第三方类。
我通过web服务(也是他们的产品之一)接收这个文件的数据。



一个解决方案是将所有这些数据写入文件并提供给班级。这是一个我不喜欢的解决方案:它取消了使用web服务的优势,而不是只是下载文件。

更快,更高效的将放这个数据从模拟文件中的内存中提供,并提供这个模拟文件给第三方类。

它可能必须是一个扩展java.io.File的MockFile,并且重载所有的功能,实际上与硬盘上的文件进行接口。



我知道第三方应该使用流作为输入参数而不是文件。然而,这是超出我的影响力。

解决方案

这只是一个基于我的理解你的问题的建议。
我相信,你必须做这样的事情,

  public void doSomething(){
/ /预处理
对象结果= new ThirdPartyCode()。actualMethod(file);
//后期处理
}

模拟对象更有意义测试视角。
您的目标不是单元测试第三方库函数。而是单元测试doSomething()方法。所以可能你可以创建一个第三方函数的包装。也许是这样的,

  public class Wrapper implements MyWrapper {

public Object invokeThirdPartyFunction(File file){
new ThirdPartyCode()。actualMethod(file);






现在你可以创建一个模拟包装器接口),并使用这个模拟包装器来处理所有的junit案例。


Does anyone have suggestions for a java mock File object? I Am using a thirdparty class which need to get a java.io.File object as argument. I receive the data for this file in a stream over a webservice (also one of their products).

One solution is to write all this data to a file and offer this to the class. This is a solution I don't like: it takes away the advantage of using the webservice in stead of just downloading the file.

Quicker and more efficient would be to put this data from memory in a Mock File and offer this Mock File to the thirdparty class.

It would probably have to be a MockFile extending the java.io.File and overriding all the functions that do actual interfacing with the file on the hard disk.

I know the thirdparty should have used a stream as an input argument in stead of a file. However, this is beyond my influence.

解决方案

This is just a suggestion based on my understanding of your question. I believe, you must be doing something like this,

public void doSomething(){
      //Pre processing
       Object result=new ThirdPartyCode().actualMethod(file);
     //Post processing
}

Mock objects make more sense from an unit testing perspective. Your objective is not to unit test the third party library function.Whereas it is to unit test doSomething() method. So probably you can create a wrapper around the third party function.Maybe something like this,

public class Wrapper implements MyWrapper{

   public Object invokeThirdPartyFunction(File file){
      new ThirdPartyCode().actualMethod(file);
   }
}

Now you can create a mock wrapper(implementing the same interface) and use this mock wrapper for all your junit cases.

这篇关于对java模拟文件的建议(模拟java.io.File)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆