How to compare two MemoryStream with FluentAssertions
Asked Answered
D

2

6

Using FluentAssertion 3.1.229, how do you compare the content of two distinct MemoryStream?

Writing actualStream.Should().Be(expectedStream); yields the following error:

System.IO.MemoryStream
{
   CanRead = True
   CanSeek = True
   CanTimeout = False
   CanWrite = True
   Capacity = 8
   Length = 8
   Position = 0
   ReadTimeout = "[Property 'ReadTimeout' threw an exception: 'Exception has been thrown by the target of an invocation.']"
   WriteTimeout = "[Property 'WriteTimeout' threw an exception: 'Exception has been thrown by the target of an invocation.']"
}, but found 

System.IO.MemoryStream
{
   CanRead = True
   CanSeek = True
   CanTimeout = False
   CanWrite = True
   Capacity = 8
   Length = 8
   Position = 0
   ReadTimeout = "[Property 'ReadTimeout' threw an exception: 'Exception has been thrown by the target of an invocation.']"
   WriteTimeout = "[Property 'WriteTimeout' threw an exception: 'Exception has been thrown by the target of an invocation.']"
}.

Yes, I could use NUnit Assert.That(actualStream, Is.EqualTo(expectedStream)); but is it possible with FluentAssertions?

Thanks.

Domella answered 2/9, 2014 at 20:9 Comment(0)
S
10

Maybe this would work for you?

actualStream.ToArray().Should().Be(expectedStream.ToArray());
Sparkie answered 2/9, 2014 at 20:30 Comment(2)
.Be() is not available on byte[] (with version 3.1.229 anyway). But with Equal(), it works.Domella
I had to compare two Stream, and it is worth to know that ToArray is not defined on Stream, but on MemoryStream. I ended up with a ToArray extension method on Stream returning new BinaryReader(stream).ReadBytes((int)stream.Length).Saran
D
0

Your NUnit solution won't work either, because MemoryStream's Equals implementation doesn't do a byte-by-byte comparison. Instead, use

actualStream.GetBuffer().ShouldBeEquivalentTo(expectedStream.GetBuffer()).

GetBuffer returns a reference to the internal byte array and calling Should().Be() on it will cause the collection assertions to do a byte-by-byte comparison.

Depurate answered 3/9, 2014 at 7:8 Comment(3)
.Be() is not available on byte[] (with version 3.1.229 anyway). With Equal(), I get this exception: System.UnauthorizedAccessException : MemoryStream's internal buffer cannot be accessed.Domella
That exception depends on the way of MemoryStream was created. Worst case you need to use ToArray() instead of GetBuffer. I've also changed my original answer because ShouldBeEquivalentTo is a bit more efficient than Should().Equal().Depurate
Inspecting the GetBuffer is a bad idea. The buffers used may potentially not be the same due to various unknowns at the time the buffer is created. Better to use ToArray() instead and check those contents since the ToAray is the final byte sequence.Chinese

© 2022 - 2024 — McMap. All rights reserved.