流测试用例上的自定义序列化和反序列化失败

时间:2019-09-14 11:59:01

标签: c#

我试图通过编写测试用例来测试我的自定义序列化和反序列化逻辑,但是无法测试是因为在反序列化期间读取流时出现此错误。

EndOfStreamException Unable to read beyond the end of the stream

我正确使用内存流还是应该使用其他流?共享代码:

[TestClass]
public class SerialTest
{
    [TestMethod]
    public void SerializationTestUsingStream()
    {
        Employee emp = new Employee(20);

        MemoryStream stream = new MemoryStream();

        this.SerializeEmployee(stream, emp);
        StreamReader reader = new StreamReader(stream);
        string text = reader.ReadToEnd(); // shows Empty string ""
        var newEmp = this.DeserializeEmployee(stream);
        emp.Should().Equals(newEmp);
    }

    private void SerializeEmployee(Stream stream, Employee collection)
    {
        using (BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8, true))
        {
            writer.Write(collection.age);
        }
    }

    private Employee DeserializeEmployee(Stream stream)
    {
        using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
        {
            int age = reader.ReadInt32(); // Exception Comes here while reading from the stream
            return new Employee(age);
        }
    }

    internal class Employee
    {
        public Employee(int age)
        {
            this.age = age;
        }

        public int age { get; set; }
    }
}

1 个答案:

答案 0 :(得分:2)

在读取流之前,您需要重置流的位置。

stream.Position = 0L;