[英]How to create unit test for class constructor in xUnit?
Say I have this class:假设我有这个 class:
public class BankAccount : IBankAccount
{
public int Id { get; private set; }
public int BankAccountNo { get; private set; }
public decimal Balance { get; private set; }
public BankAccount(int BankAccountNo, decimal Balance)
{
this.BankAccountNo = BankAccountNo;
if(Balance <= 0)
{
throw new ArgumentException("Create bank account failed. Balance should be more than zero.");
}
this.Balance = Balance;
}
public void Deposit(BankTransaction bankTransaction)
{
if (bankTransaction.TransactionAmount <= 0)
{
throw new ArgumentException("Deposit failed. Transaction amount is more than account balance.");
}
this.Balance += bankTransaction.TransactionAmount;
// Insert transaction record at BankTransaction Repository class
}
}
My previous design is Deposit have BankAccount
in the method parameter.我之前的设计是在方法参数中存款有BankAccount
。 With this design, I could create unit test for Deposit
method as below:通过这种设计,我可以为Deposit
方法创建单元测试,如下所示:
[Theory, MemberData(nameof(DepositShouldPass_Data))]
public void DepositShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
{
// Act
_bankAccount.Deposit(account, bankTransaction);
// Assert
Assert.Equal(accountExpected.Balance, _bankAccount.Balance);
}
public static TheoryData<BankAccount, BankTransaction, BankAccount> DepositShouldPass_Data()
{
return new TheoryData<BankAccount, BankTransaction, BankAccount>
{
{
new BankAccount(123, 250.00M),
new BankTransaction(50.00M),
new BankAccount(123, 300.00M)
},
{
new BankAccount(321, 150.50M),
new BankTransaction(10.50M),
new BankAccount(321, 160.00M)
}
};
}
But now, I want to re-design BankAccount
class by removing BankAccount
as method parameter in Deposit
method.但是现在,我想重新设计BankAccount
class 通过删除BankAccount
作为Deposit
方法中的方法参数。 With this new design, how do I pass test data using xUnit?有了这个新设计,我如何使用 xUnit 传递测试数据? Secondly is how do I create unit test for my constructor?其次是如何为我的构造函数创建单元测试?
You can try this:你可以试试这个:
var bankAccountNo = new Random().Next();
var balance = 0;
BankAccount TestCode() => new BankAccount(bankAccountNo, balance);
var exception = Assert.Throws<ArgumentException>(TestCode);
Assert.StartsWith("Create bank account failed. Balance should be more than zero.", exception.Message);
And this:和这个:
var bankAccountNo = new Random().Next();
var balance = new Random().Next();
var bankAccount = new BankAccount(bankAccountNo, balance);
Assert.Equal(bankAccountNo, bankAccount.BankAccountNo);
Assert.Equal(balance, bankAccount.Balance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.