试图模拟FileWriter会抛出NullPointerException

时间:2016-05-05 00:13:32

标签: java unit-testing jmockit

我正在尝试模拟FileWriter和BufferedWriter构造函数API。每当我尝试模拟FileWriter API时,我都会在堆栈跟踪中看到NPE异常。

下面给出了异常堆栈跟踪。

java.lang.NullPointerException
at java.io.Writer.<init>(Writer.java:99)
at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:115)
at java.io.FileWriter.<init>(FileWriter.java)
at com.boa.service.EmployeeServiceTest.writeToFile(EmployeeServiceTest.java:206)
at com.boa.service.EmployeeServiceTest.testWriteToFile_Success(EmployeeServiceTest.java:201)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:613)

源代码如下:

  void writeToFile(String filename, Set<Employee> employees) throws Exception {        
    try(
        Writer writer = new FileWriter(filename);
        BufferedWriter writer = new BufferedWriter(writer);) {
        for (Employee employee : employees) {
            StringBuilder sb = new StringBuilder();
            sb.append(employee.getLastName()).append(", ").
                append(employee.getFirstName()).append("\n");
            writer.write(sb.toString());
        }
    } catch (IOException e) {
      throw new IOException(
         "unable to write to file : " + filename, e);
    }
  }

我的单元测试如下:

  @Test
  public void testWriteToFile_Success()
      throws Exception {
    FileWriterMock wMock = new FileWriterMock();
    BufferedWriterMock bwMock = new BufferedWriterMock();
    Employee employee = new Employee("firstName", "lastName");
    Set<Employee> employees = new TreeSet<>();
    employees.add(employee);
    this.writeToFile("test-filename.csv", employees);     
  }

class FileWriterMock extends MockUp<FileWriter> {
    String filename;
    @Mock
    public void $init(String filename) {
      System.out.println("writer constructor");
      this.filename = filename;
    }
  }

  class BufferedWriterMock extends MockUp<BufferedWriter> {

    private int writerCount = 0;


    public int getWriterCount() {
      return writerCount;
    }

    @Mock
    public void $init(Writer writer) {
      System.out.println("buffered writer constructor");
    }

    @Mock
    public void write(String str) {
      this.writerCount ++;
    }
  }

我尝试在此示例中使用jMockit's Faking Tutorials。但是,我不知道自己做错了什么。我正在使用带有eclipse的TestNG插件。

0 个答案:

没有答案