测试用例以进行转换?

huangapple go评论55阅读模式
英文:

Test case for a trans?

问题

我在服务类中有一个转账方法,我想为这个方法创建一个测试,以检查转账金额是否有效。

我想要测试的方法是这个:

public void transfer(Account destiny, double value) {
    Account origin = new Account();
    if (value <= origin.getBalance()) {
        this.withdraw(value);
        destiny.setDeposit(value);
    }
}

我现在开始尝试编写测试代码。感谢您的理解。

英文:

I have the transfer method in the service class and I would like to create a test for this method, to check if the transfer value is valid.

The method I would like to test is this:

public void transfer(Account destiny, double value) {
        Account origin = new Account();
        if (value&lt;= origin.getBalance()) {
            this.withdraw(value);
            destiny.setDeposit(value);
        }
    }

I am now starting to tinker with tests. thanks for the comprehension.

答案1

得分: 1

我首先建议您重构那个方法。
不要在方法内部实例化/创建/查找原始账户,而是希望将其作为参数传递。
因此,您的新方法签名应如下所示:

public void transfer(Account destiny, Account origin, double value) {
   ...
}

完成后,您的正向路径测试用例应如下所示:

Account destiny = new Account();
destiny.setBalance(100); // 设置余额的某种方式
Account origin = new Account();
origin.setBalance(75); // 设置余额的某种方式

transfer(destiny, origin, 25); // 调用您的方法

assertEquals(origin.getBalance(), 50);
assertEquals(destiny.getBalance(), 125);

您还可以在这里测试负面情况,即原始余额小于转账金额,因此不会发生转账,两个账户的余额都不会改变。

英文:

I would first recommend that you refactor that method.
Instead of instantiating/creating/finding the origin account inside the method, you want to pass that in.
So your new method signature should look as following

public void transfer(Account destiny, Account origin, double value) {
   ...
}

Once that's done your happy path test case should look something like this

Account destiny = new Account();
destiny.setBalance(100); // Some way to set balance
Account origin = new Account();
origin.setBalance(75); // Some way to set balance

transfer(destiny,origin,25); //Call your method

assertEquals(origin.getBalance(), 50);
assertEquals(origin.getBalance(), 125);

You can also test the negative case here where the origin balance is less than the transfer amount so the transfer doesn't happen and the balance on both accounts is unchanged.

答案2

得分: 0

以下是翻译好的内容:

如何检查余额是否已更改
英文:

How about this, check the balance has changed

Account origin = new Account();
double originBalance = origin.getBalance();

transfer(destiny, value);

Account current = new Account();
double currentBalance = current.getBalance();

// Balance should have changed
assertNotEquals(originBalance, currentBalance, 1e-15);

huangapple
  • 本文由 发表于 2020年9月22日 00:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63995986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定