5

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.

dstj
  • 4,800
  • 2
  • 39
  • 61

2 Answers2

9

Maybe this would work for you?

actualStream.ToArray().Should().Be(expectedStream.ToArray());
Jay Otterbein
  • 948
  • 5
  • 10
  • 2
    .Be() is not available on byte[] (with version 3.1.229 anyway). But with Equal(), it works. – dstj Sep 04 '14 at 14:14
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.

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • .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.` – dstj Sep 04 '14 at 14:13
  • 1
    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()`. – Dennis Doomen Sep 04 '14 at 18:42
  • 1
    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. – enorl76 Sep 19 '19 at 18:24