3
我使用手寫的假貨演示應用程序,但我不確定我是否正確使用模擬。這裏是我下面的代碼:打電話並將其用作存根或模擬是否正確?
[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);
}
}
}
第二個測試實例假冒是指它作爲模擬,然後調用驗證方法。這種方法是對還是錯?
謝謝。我只需要一個確認 – peter 2014-10-30 09:23:46
@peter如果你對一個存根和一個模擬之間的區別感興趣,在古典意義上你有一個模擬。具有諷刺意味的是,大多數嘲諷框架(我特別瞭解Moq)協助創建存根,儘管他們稱之爲嘲諷。請參閱http://martinfowler.com/articles/mocksArentStubs.html以瞭解這兩個術語之間的徹底對比。 – 2014-11-02 01:31:40
我知道不同之處。我可以使用框架輕鬆創建這些 – peter 2014-11-04 16:51:24