![](/img/trans.png)
[英]Is it threadsafe to add to a ConcurrentDictionary using foo[bar] = baz?
[英]Function under test “foo” calls external function “bar(baz)” multiple times => How can return value of “baz” be modified specifically for each call?
假设我有以下 function "foo" 我想对其进行单元测试:
class FooClass
{
IBar _bar;
Foo(IBar bar)
{
_bar = bar;
}
void foo()
{
byte[] someBytes;
someBytes = _bar.ReadBytes();
if (someBytes != Expectation1)
{
throw new Exception("Byte stream doesn't match expectations");
}
someBytes = _bar.ReadBytes();
if (someBytes != Expectation2)
{
throw new Exception("Byte stream doesn't match expectations");
}
...
}
}
“_bar.ReadBytes”将读取一些期望特定字节流的数据,这些数据将在每次“ReadBytes”调用后在 foo 中进行评估。
现在,在单元测试中调用“foo”时,如何以特定方式每次影响“ReadBytes”的返回值? 如何设置模拟?
所以为了测试我需要做一些类似的事情......
public class FooClassTests
{
[Fact]
public void Test_Foo()
{
Mock<IBar> mockBar = new Mock<IBar>();
mockComInterface.Setup(mock => mock.ReadBytes()).Returns(new byte[] {}); // returns empty byte array
FooClass fooObject = new FooClass();
fooObject.foo();
Assert.something...
}
}
看起来SetupSequence
是您正在寻找的
//...
Mock<IBar> mockBar = new Mock<IBar>();
mockBar.SetupSequence(mock => mock.ReadBytes())
.Returns(expectation1ByteArray) // will be returned on 1st invocation
.Returns(expectation2ByteArray); // will be returned on 2nd invocation
FooClass fooObject = new FooClass(mockBar.Object);
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.