将对象转换为模拟流

问题描述 投票:0回答:1

下面给出的是我的对象类。这里我试图将此对象类转换为模拟流

    public class WebHookBody
    {
        public string entryId { get; set; }
    }

我正在尝试在下面的代码上添加模拟,但我不能

var wasCalled = false;
            
var mockStream = new Mock<Stream>();
mockStream.Setup(s => s.CanWrite).Returns(true);
mockStream.Setup(s => s.Write(It.IsAny<byte[]>(),
    It.IsAny<int>(),
    It.IsAny<int>())).Callback((byte[] bytes, int offs, int c) =>
    {
        wasCalled = true;
    });```

converted mock stream for a given object class
c# testing mocking stream
1个回答
0
投票

我建议不要使用

wasCalled
变量。相反,您可以使用
Verify
方法来断言调用了特定方法:

[Test]
public void Test()
{
    var mockStream = new Mock<Stream>();
    mockStream.Setup(s => s.CanWrite).Returns(true);

    mockStream.Object.Write([1, 2, 3], 0, 100);

    // Assert that Write was called at least once.
    mockStream.Verify(
        s => s.Write(
            It.IsAny<byte[]>(),
            It.IsAny<int>(),
            It.IsAny<int>()),
        Times.AtLeastOnce);
}
© www.soinside.com 2019 - 2024. All rights reserved.