小编Mat*_*ril的帖子

用Java模拟文件 - 模拟内容 - Mockito

我很嘲笑,我一直在尝试模拟实际内容(本质上只在内存中创建一个虚拟文件),这样就不会在任何时候将数据写入磁盘.

我已经尝试过像模拟文件和模拟尽可能多的我可以解决的许多属性的解决方案,然后用文件编写器/缓冲区写入器写入它,但是那些不能正常工作,因为它们需要规范路径.有人找到了这个或类似的解决方案,但我接近这个错误?

我一直在这样做:

private void mocking(){
    File badHTML = mock(File.class);
    //setting the properties of badHTML
    when(badHTML.canExecute()).thenReturn(Boolean.FALSE);
    when(badHTML.canRead()).thenReturn(Boolean.TRUE);
    when(badHTML.canWrite()).thenReturn(Boolean.TRUE);
    when(badHTML.compareTo(badHTML)).thenReturn(Integer.SIZE);
    when(badHTML.delete()).thenReturn(Boolean.FALSE);
    when(badHTML.getFreeSpace()).thenReturn(0l);
    when(badHTML.getName()).thenReturn("bad.html");
    when(badHTML.getParent()).thenReturn(null);
    when(badHTML.getPath()).thenReturn("bad.html");
    when(badHTML.getParentFile()).thenReturn(null);
    when(badHTML.getTotalSpace()).thenReturn(0l);
    when(badHTML.isAbsolute()).thenReturn(Boolean.FALSE);
    when(badHTML.isDirectory()).thenReturn(Boolean.FALSE);
    when(badHTML.isFile()).thenReturn(Boolean.TRUE);
    when(badHTML.isHidden()).thenReturn(Boolean.FALSE);
    when(badHTML.lastModified()).thenReturn(System.currentTimeMillis());
    when(badHTML.mkdir()).thenReturn(Boolean.FALSE);
    when(badHTML.mkdirs()).thenReturn(Boolean.FALSE);
    when(badHTML.setReadOnly()).thenReturn(Boolean.FALSE);
    when(badHTML.setExecutable(true)).thenReturn(Boolean.FALSE);
    when(badHTML.setExecutable(false)).thenReturn(Boolean.TRUE);
    when(badHTML.setReadOnly()).thenReturn(Boolean.FALSE);

    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(badHTML));
        /*
          badHTMLText is a string with the contents i want to put into the file, 
          can be just about whatever you want
         */
        bw.append(badHTMLText);
        bw.close();

    } catch (IOException ex) {
        System.err.println(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

任何想法或指导都会非常有帮助.在此之后的某个地方我基本上尝试使用另一个类从文件中读取.我会尝试模拟某种输入流,但另一类不接受输入流,因为它是项目的io处理类.

java file mockito

28
推荐指数
2
解决办法
7万
查看次数

多态数据结构Java

我试图使用动态给出的泛型类型作为给定数据结构的类型,类似于函数中的映射,但在声明时只使用一个类.它更像是带键的ArrayList.所以,我试图做的是:

private final ArrayList<T extends Object> findGroup(final String key, final String classType)
{
     Class<?> c = Class.forName(classType);
     ArrayList<c.class> listOfStuff = new ArrayList<>();

     return listOfStuff;
 }
Run Code Online (Sandbox Code Playgroud)

我得到的错误发生在.class调用上.我已经尝试过c.getClass(),以及从c.class创建另一个Class对象只是为了查看它是否有效,但无法使其正常工作.

有一些首选的方法吗?

是的,我知道其中一些往往有点繁重,但我需要它来做我正在做的事情.

java generics reflection polymorphism data-structures

0
推荐指数
1
解决办法
77
查看次数