导入org.junit时出错,Assert

c9qzyr3d  于 2022-11-11  发布在  其他
关注(0)|答案(4)|浏览(238)

教授给我的单元测试出了点小问题。编译时,我收到了以下错误:
cannot find symbol import org.junit.Assert.assertArrayEquals; cannot find symbol import org.junit.Assert.assertEquals; import org.junit.Assert.assertFalse; import org.junit.Assert.assertTrue;
我已经下载了JUnit,并且可以编译一个类似的文件,那么为什么我会遇到问题呢?代码是:

  1. import java.util.Comparator;
  2. import org.junit.Assert.assertArrayEquals;
  3. import org.junit.Assert.assertEquals;
  4. import org.junit.Assert.assertFalse;
  5. import org.junit.Assert.assertTrue;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. public class SortingTests {
  9. class IntegerComparator implements Comparator<Integer> {
  10. @Override
  11. public int compare(Integer i1, Integer i2) {
  12. return i1.compareTo(i2);
  13. }
  14. }
  15. private Integer i1,i2,i3;
  16. private OrderedArray<Integer> orderedArray;
  17. @Before
  18. public void createOrderedArray(){
  19. i1 = -12;
  20. i2 = 0;
  21. i3 = 4;
  22. orderedArray = new OrderedArray<>(new IntegerComparator());
  23. }
  24. @Test
  25. public void testIsEmpty_zeroEl(){
  26. assertTrue(orderedArray.isEmpty());
  27. }
  28. @Test
  29. public void testIsEmpty_oneEl() throws Exception{
  30. orderedArray.add(i1);
  31. assertFalse(orderedArray.isEmpty());
  32. }
  33. @Test
  34. public void testSize_zeroEl() throws Exception{
  35. assertEquals(0,orderedArray.size());
  36. }
  37. }
nlejzf6q

nlejzf6q1#

假设类路径中有JUnit dependency,请对assert方法使用import static

  1. import static org.junit.Assert.assertArrayEquals;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertFalse;
  4. import static org.junit.Assert.assertTrue;

或者简单地用途:

  1. import static org.junit.Assert.*;
c2e8gylq

c2e8gylq2#

您要查找的是 * 静态导入 *
import org.junit.Assert.assertArrayEquals;正在引用org.junit.Assert类中的assertArrayEquals方法
导入一个静态方法,使其像assertEquals(0,orderedArray.size());一样可调用,这是通过静态导入行完成的。请尝试以下操作:

  1. import static org.junit.Assert.assertArrayEquals;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertFalse;
  4. import static org.junit.Assert.assertTrue;

或者,您可以:

  1. import static org.junit.Assert.*;

,或者您可以:

  1. import org.junit.Assert;

并引用以下方法

  1. Assert.assertEquals(0,orderedArray.size());
展开查看全部
kuarbcqp

kuarbcqp3#

您应该添加关键字static来导入它。示例:

  1. import static org.junit.Assert.assertFalse;
olqngx59

olqngx594#

如果您使用的是junit版本5或更高版本,那么请使用org.junit.jupiter.api.assertions。
路径已在junit 5中移动

相关问题