ObjectInputStream 测试的 EOF 异常

EOF Exception for ObjectInputStream test

我正在尝试测试 readObjectObjectInputStream

读取对象的方法
@Test
public void testReadObject() throws Exception {
    ObjectInputStream in = new ObjectInputStream(System.in);
...
} 

我正在为 ObjectInputStream in = new ObjectInputStream(System.in); 中的 ObjectInputStream 获取 java.io.EOFException

我是在嘲笑 ObjectInputStream 还是一种不好的做法? 我如何编写测试用例以涵盖整个 readObject 场景?

我的员工class:

public class Employee {

private Object Teacher;
...
private void readObject(java.io.ObjectInputStream in) throws Exception {
    Teacher = in.readObject();
 }
...
}

请注意,我使用的是 JUnit 和 Mockito。

我的方法需要更多的测试代码,但它让您有机会在不模拟的情况下编写测试 ObjectInputStream:

@Test
void testReadObject() throws Exception {
    String teacherObject = "TeacherObject";
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    new ObjectOutputStream(outputStream).writeObject(teacherObject);
    final Employee employee = new Employee();

    employee.readObject(
        new ObjectInputStream(
            new ByteArrayInputStream(
                outputStream.toByteArray()
            )
        )
    );

    assertEquals(teacherObject, employee.getTeacher());
}

注意:这个测试是在两个假设下编写的:

  1. Employeeclass有方法getTeacher()。因为你需要以某种方式断言 Teacher 是从 ObjectInputStream 中正确读取的。如果您有其他方法,请根据您的需要修改我的示例。
  2. Employee.readObject() 方法可见度为 public。这样做只是为了简化我的例子。在您的问题中,readObject() 具有私人可见性。您可以根据需要修改我的示例,或者给我更多的上下文,以便我可以相应地修改我的示例。

完整源代码:

  1. Employee.java
package dev.iakunin.Whosebug.question;

public class Employee {

    private Object teacher;

    public void readObject(java.io.ObjectInputStream in) throws Exception {
        teacher = in.readObject();
    }

    public Object getTeacher() {
        return teacher;
    }
}
  1. EmployeeTest.java
package dev.iakunin.Whosebug.question;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class EmployeeTest {

    @Test
    void testReadObject() throws Exception {
        String teacherObject = "TeacherObject";
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        new ObjectOutputStream(outputStream).writeObject(teacherObject);
        final Employee employee = new Employee();

        employee.readObject(
            new ObjectInputStream(
                new ByteArrayInputStream(
                    outputStream.toByteArray()
                )
            )
        );

        assertEquals(teacherObject, employee.getTeacher());
    }
}