[英]JUnit assertEquals() is failing even though they appear to be equal
[英]JUnit = red bar, even if my assertEquals is correct
package dpackage;
public class MyCalculator {
public int getSum(int a, int b, int sum) {
sum = a+b;
return sum;
}
}
package dpackage;
import junit.framework.TestCase;
public class MyCalculatorTest extends TestCase {
MyCalculator calc = new MyCalculator();
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
protected void getSum(){
int a=2;
int b=3;
int sum = a+b;
assertEquals(5, calc.getSum(a, b, sum));
}
}
原因有点微妙。 将代码更改为以下以获得绿色条。
public void testGetSum()
在Junit 3中,测试方法应该从test
开始并public
如果可能的话,我会建议你继续使用Junit 4,它不会施加这样的限制。
使用注释,比如@Test
, @Before
和@After
你的代码会更简单,更易于阅读。
在又路过sum
的方法,然后重新计算它看起来是多余的。 坚持在你的getSum
方法中计算它。
您没有任何名称以“test”开头的方法。 您可以在MyCalculatorTest类中将“getSum”方法重命名为“testGetSum”。
这个定义有什么意义?
public int getSum(int a, int b, int sum) {
sum = a+b;
return sum;
}
只需使用:
public int getSum(int a, int b) {
return a + b;
}
和
public void testGetSum() { <-- note test in front
int a=2;
int b=3;
assertEquals(5, calc.getSum(a, b));
}
请注意,在方法前面没有test
的eclipse报告的错误是没有检测到测试类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.