tx1.Write
和
tx2.Write
在上面,您可以轻松地检查每个事务是否被调用一次,这可能比检查总共调用了两次更有用:
public void Test()
{
var realStore = new RealStore();
var fakeStore = A.Fake<Store>(x => x.Wrapping(realStore));
var realTransaction1 = new RealTransaction();
var realTransaction2 = new RealTransaction();
var wrappedTransaction1 = A.Fake<Tx>(options => options.Wrapping(realTransaction1));
var wrappedTransaction2 = A.Fake<Tx>(options => options.Wrapping(realTransaction2));
A.CallTo(() => fakeStore.BeginTx())
.Returns(wrappedTransaction1).Once().Then
.Returns(wrappedTransaction2);
WriteALot(fakeStore);
A.CallTo(() => wrappedTransaction1.Write()).MustHaveHappenedOnceExactly();
A.CallTo(() => wrappedTransaction2.Write()).MustHaveHappenedOnceExactly();
}
但是如果您真的想确保两个调用都是在不检查每个事务是否负责一次写入的情况下进行的,那么您可以
[Test]
public void LaxTest()
{
int numberOfTransactionCalls = 0;
var realStore = new RealStore();
var fakeStore = A.Fake<Store>(x => x.Wrapping(realStore));
var realTransaction1 = new RealTransaction();
var realTransaction2 = new RealTransaction();
var wrappedTransaction1 = A.Fake<Tx>(options => options.Wrapping(realTransaction1));
var wrappedTransaction2 = A.Fake<Tx>(options => options.Wrapping(realTransaction2));
A.CallTo(() => wrappedTransaction1.Write()).Invokes(() => ++numberOfTransactionCalls);
A.CallTo(() => wrappedTransaction2.Write()).Invokes(() => ++numberOfTransactionCalls);
A.CallTo(() => fakeStore.BeginTx())
.Returns(wrappedTransaction1).Once().Then
.Returns(wrappedTransaction2);
WriteALot(fakeStore);
Assert.That(numberOfTransactionCalls, Is.EqualTo(2));
}
[Test]
public void UnwrappedTest()
{
var fakeStore = A.Fake<Store>();
var transaction1 = A.Fake<Tx>();
var transaction2 = A.Fake<Tx>();
A.CallTo(() => fakeStore.BeginTx())
.Returns(transaction1).Once().Then
.Returns(transaction2);
WriteALot(fakeStore);
A.CallTo(() => transaction1.Write()).MustHaveHappenedOnceExactly();
A.CallTo(() => transaction2.Write()).MustHaveHappenedOnceExactly();
}
在我看来,理解发生了什么要容易得多。但也许你只是为了问问题而简化了。