Skip to content

Instantly share code, notes, and snippets.

@tomspilman
Last active December 13, 2015 16:49
Show Gist options
  • Save tomspilman/4942988 to your computer and use it in GitHub Desktop.
Save tomspilman/4942988 to your computer and use it in GitHub Desktop.
Unit test to verify the balance of BinaryReader/Writer for char arrays. Could be expanded to form a complete balance test for all calls.
[TestClass]
public class BinaryReaderWriterBalance
{
class TestBinaryWriter : BinaryWriter
{
private int _counter;
public TestBinaryWriter(Stream output)
: base(output)
{
}
public override void Write(char[] chars)
{
base.Write(_counter++);
base.Write(chars);
}
public override void Write(char[] chars, int index, int count)
{
base.Write(_counter++);
base.Write(chars, index, count);
}
}
class TestBinaryReader : BinaryReader
{
private int _counter;
public TestBinaryReader(Stream input)
: base(input)
{
}
public override char[] ReadChars(int count)
{
Assert.AreEqual(_counter++, base.ReadInt32());
return base.ReadChars(count);
}
public override int Read(char[] buffer, int index, int count)
{
Assert.AreEqual(_counter++, base.ReadInt32());
return base.Read(buffer, index, count);
}
}
[TestMethod]
public void TestCharReadWriteBalance()
{
var stream = new MemoryStream();
var writeChars = "TEST".ToCharArray();
var writer = new TestBinaryWriter(stream);
writer.Write(writeChars);
writer.Write(writeChars, 0, writeChars.Length);
stream.Seek(0, SeekOrigin.Begin);
var reader = new TestBinaryReader(stream);
var readChars = reader.ReadChars(writeChars.Length);
reader.Read(readChars, 0, writeChars.Length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment