gpt4 book ai didi

java - 如何在 junit 测试中测试 Comparator

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:56 25 4
gpt4 key购买 nike

我需要测试这个方法 - compare()。你能得到建议吗?我能做得多好(所有部分如果,否则-如果,否则)。

public class AbsFigure {

class AreaCompare implements Comparator<FigureGeneral> {

@Override
public int compare(FigureGeneral oneFigure, FigureGeneral twoFigure) {
double firstValue = oneFigure.area();
double secondValue = twoFigure.area();
int result = 0;

if (firstValue > secondValue)
result = 1;
else if (firstValue < secondValue)
result = -1;
else
result = 0;

return result;
}
}

在这些建议之后 - 我们有下一张照片(非常感谢你们!):

public AreaCompare areaCompare = new AreaCompare();

@Test
public void testEqual() {
FigureGeneral oneFigure = new Rectangle(2.0, 2.0, "triangle");
FigureGeneral twoFigure = new Rectangle(2.0, 2.0, "rectangle");
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be equal", result == 0);
}

@Test
public void testGreaterThan() {
FigureGeneral oneFigure = new Triangle(2.0, 2.0, "triangle");
FigureGeneral twoFigure = new Rectangle(1.0, 1.0, "rectangle");
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be greater than", result >= 1);
}

@Test
public void testLessThan() {
FigureGeneral oneFigure = new Rectangle(1.0, 1.0, "rectangle");
FigureGeneral twoFigure = new Triangle(2.0, 2.0, "triangle");
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be less than", result <= -1);

现在一切正常测试。

最佳答案

只需实例化您的比较器类并传入对象:

public class Test extends TestCase {
class AreaCompare implements Comparator<FigureGeneral> {

@Override
public int compare(FigureGeneral oneFigure, FigureGeneral twoFigure) {
double firstValue = oneFigure.area();
double secondValue = twoFigure.area();
int result = 0;

if (firstValue > secondValue) {
result = 1;
} else if (firstValue < secondValue) {
result = -1;
} else {
result = 0;
}

return result;
}
}

private final AreaCompare areaCompare = new AreaCompare();

@Test
public void testEqual() {
FigureGeneral oneFigure = new FigureGeneral();
FigureGeneral twoFigure = new FigureGeneral();
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be equal", result == 0);
}

@Test
public void testGreaterThan() {
FigureGeneral oneFigure = new FigureGeneral();
FigureGeneral twoFigure = new FigureGeneral();
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be greater than", result >= 1);
}

@Test
public void testLessThan() {
FigureGeneral oneFigure = new FigureGeneral();
FigureGeneral twoFigure = new FigureGeneral();
int result = areaCompare.compare(oneFigure, twoFigure);
assertTrue("expected to be less than", result <= -1);
}
}

关于java - 如何在 junit 测试中测试 Comparator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14144914/

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