要測試Java中的compare
方法的正確性,你可以編寫一個單元測試類,使用JUnit框架進行測試。以下是一個示例:
pom.xml
文件中添加以下依賴:<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
Comparator
接口的類,例如MyComparator
,并實現compare
方法:import java.util.Comparator;
public class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
MyComparatorTest
,并編寫測試方法:import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MyComparatorTest {
@Test
void testCompare() {
MyComparator comparator = new MyComparator();
// 測試正數
int result1 = comparator.compare(3, 2);
assertEquals(1, result1, "3 should be greater than 2");
// 測試負數
int result2 = comparator.compare(1, 3);
assertEquals(-1, result2, "1 should be less than 3");
// 測試相等
int result3 = comparator.compare(2, 2);
assertEquals(0, result3, "2 should be equal to 2");
}
}
MyComparatorTest
,查看測試結果。如果所有測試通過,那么你的compare
方法應該是正確的。