gpt4 book ai didi

java - 如何在 Junit 测试中测试构造函数?

转载 作者:行者123 更新时间:2023-12-01 22:38:57 26 4
gpt4 key购买 nike

如何在 Junit4 测试用例中测试这个 Fraction 构造函数?谢谢!

public class Fraction {

private int num;
private int den;

public Fraction(int num,int den){
this.num=num;
this.den=den;
if(den==0){
this.den=1;
System.out.println("ERROR: DENOMINATOR CAN NOT BE 0");
System.out.println("Now the fraction is changed to"+toString());
}
}
}

最佳答案

我将运行构造函数,然后检查分母是否包含您期望的值:

public class FractionTest() {
private Fraction f;

@Test
public void testLegalConstruction() {
f = new Fraction (4, 7);
assertEquals ("wrong num", 4, f.getNum());
assertEquals ("wrong den", 7, f.getDen());

@Test
public void testIlegalConstruction() {
f = new Fraction (3, 0);
assertEquals ("wrong num", 3, f.getNum());
assertEquals ("wrong den", 1, f.getDen()); // Note the 1
}

关于java - 如何在 Junit 测试中测试构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com