我使用手写假货作为演示应用,但我不确定我是否正确使用了模拟。这是我的代码:
[Fact]
public void TransferFund_WithInsufficientAccountBalance_ThrowsException()
{
IBankAccountRepository stubRepository = new FakeBankAccountRepository();
var service = new BankAccountService(stubRepository);
const int senderAccountNo = 1, receiverAccountNo = 2;
const decimal amountToTransfer = 400;
Assert.Throws<Exception>(() => service.TransferFund(senderAccountNo, receiverAccountNo, amountToTransfer));
}
[Fact]
public void TransferFund_WithSufficientAccountBalance_UpdatesAccounts()
{
var mockRepository = new FakeBankAccountRepository();
var service = new BankAccountService(mockRepository);
const int senderAccountNo = 1, receiverAccountNo = 2;
const decimal amountToTransfer = 100;
service.TransferFund(senderAccountNo, receiverAccountNo, amountToTransfer);
mockRepository.Verify();
}
测试双倍:
public class FakeBankAccountRepository : IBankAccountRepository
{
private List<BankAccount> _list = new List<BankAccount>
{
new BankAccount(1, 200),
new BankAccount(2, 400)
};
private int _updateCalled;
public void Update(BankAccount bankAccount)
{
var account = _list.First(a => a.AccountNo == bankAccount.AccountNo);
account.Balance = bankAccount.Balance;
_updateCalled++;
}
public void Add(BankAccount bankAccount)
{
if (_list.FirstOrDefault(a => a.AccountNo == bankAccount.AccountNo) != null)
throw new Exception("Account exist");
_list.Add(bankAccount);
}
public BankAccount Find(int accountNo)
{
return _list.FirstOrDefault(a => a.AccountNo == accountNo);
}
public void Verify()
{
if (_updateCalled != 2)
{
throw new Xunit.Sdk.AssertException("Update called: " + _updateCalled);
}
}
}
第二个测试实例化假冒并将其称为mock,然后调用verify方法。这种做法是对还是错?
答案 0 :(得分:3)
这就是模拟框架的工作原理
Expect
- 家庭方法完成)以及稍后Verify
他们(您的第二次测试)Stub
,Setup
),因为它在流程中是必要的(您的第一次测试)这种方法是正确的,但它又重新发明了轮子。除非你有充分的理由这样做,否则我会花一些时间学习并使用一个模拟框架(Moq或FakeItEasy)。