2014-09-02 68 views
0

使用FluentAssertion 3.1.229,你如何比较两个不同的MemoryStream内容如何比较两个MemoryStream与FluentAssertions

写作actualStream.Should().Be(expectedStream);产生以下错误:

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.']" 
}. 

是的,我可以使用NUnit Assert.That(actualStream, Is.EqualTo(expectedStream));但有可能与FluentAssertions?

谢谢。

回答

0

也许这会适合你吗?

actualStream.ToArray().Should().Be(expectedStream.ToArray()); 
+0

.Be()在byte []上不可用(无论如何版本为3.1.229)。但通过Equal(),它可以工作。 – dstj 2014-09-04 14:14:29

0

你NUnit的解决方案将不能工作,因为MemoryStreamEquals实现并不做一个逐字节的比较。相反,使用

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

GetBuffer返回对内部字节数组的引用并在其上调用Should().Be()将导致集合断言进行逐字节比较。

+0

.Be()在byte []上不可用(无论如何版本为3.1.229)。使用Equal(),我得到这个异常:'System.UnauthorizedAccessException:MemoryStream的内部缓冲区不能被访问。' – dstj 2014-09-04 14:13:09

+0

这个异常取决于'MemoryStream'的创建方式。最糟糕的情况是你需要使用'ToArray()'而不是'GetBuffer'。我也改变了我原来的答案,因为'ShouldBeEquivalentTo'比'Should()。Equal()'更有效率。 – 2014-09-04 18:42:10