IntelliJ 测试失败
IntelliJ test fails
您好,我正在尝试使用测试用例测试我的 Calculator.java class,但出现此错误:
java.lang.AssertionError:预期:<3> 但 was:main.Calculator@5bb21b69
预期:3
实际:main.Calculator@5bb21b69
这是我写的测试用例
public class CalculatorTest {
@Test
public void testCalculator(){
Calculator calculator = new Calculator();
calculator.calculate(5,2,'-');
Assert.assertEquals(3,calculator);
}
这是我的计算器class
package main;
public class Calculator {
public Double calculate(double first, double second, char operator) {
double result;
switch (operator) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
System.out.printf("Error! operator is not correct");
return null;
}
return result;
}
}
您试图断言您的测试结果 3
等于您的 calculator
对象。您希望断言的第二个参数是计算出的 value,而不是 calculator
对象。
public class CalculatorTest {
@Test
public void testCalculator() {
Calculator calculator = new Calculator();
double actual = calculator.calculate(5, 2, '-');
Assert.assertEquals(3.0, actual);
}
}
而且这个测试会失败,因为你除的是双精度数,而不是整数。
你有两个问题:
实际值错误
浮点数双重比较错误
Calculator calculator = new Calculator();
double value = calculator.calculate(5,2,'-'); // use result from calculation
Assert.assertTrue(Math.abs(3 - value) <= 0.000001);
您好,我正在尝试使用测试用例测试我的 Calculator.java class,但出现此错误:
java.lang.AssertionError:预期:<3> 但 was:main.Calculator@5bb21b69 预期:3 实际:main.Calculator@5bb21b69
这是我写的测试用例
public class CalculatorTest {
@Test
public void testCalculator(){
Calculator calculator = new Calculator();
calculator.calculate(5,2,'-');
Assert.assertEquals(3,calculator);
}
这是我的计算器class
package main;
public class Calculator {
public Double calculate(double first, double second, char operator) {
double result;
switch (operator) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
System.out.printf("Error! operator is not correct");
return null;
}
return result;
}
}
您试图断言您的测试结果 3
等于您的 calculator
对象。您希望断言的第二个参数是计算出的 value,而不是 calculator
对象。
public class CalculatorTest {
@Test
public void testCalculator() {
Calculator calculator = new Calculator();
double actual = calculator.calculate(5, 2, '-');
Assert.assertEquals(3.0, actual);
}
}
而且这个测试会失败,因为你除的是双精度数,而不是整数。
你有两个问题:
实际值错误
浮点数双重比较错误
Calculator calculator = new Calculator(); double value = calculator.calculate(5,2,'-'); // use result from calculation Assert.assertTrue(Math.abs(3 - value) <= 0.000001);