Is it correct to call and use this as a stub or mock?
I am using handwritten forgeries for the demo application, but I am not sure if I am using the mock appropriately. Here's my code below:
[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();
}
Double test:
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);
}
}
}
the second test creates a fake and refers to it as a mock, then it calls the validator method. Is this approach right or wrong?
+3
source to share
1 answer
How mocking frameworks work
- You either make assumptions about the interactions between the components (this is usually done with various
Expect
-family methods ) and thenVerify
them (your second test) - Or are you saying that your double test behaves in a certain way (
Stub
,Setup
) because it needs to be in a thread (your first test)
The approach is correct, but it reinvents the wheel again. Unless you have a good reason to do this, I would spend some time learning and using one of the mocking frameworks ( Moq or FakeItEasy ).
+3
source to share