2014-09-02 41 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