2017-04-09 61 views
3

我的教授给我的单元测试有点问题。在编译时,我收到以下错误:
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;导入org.junit.Assert时出错

我已经下载了JUnit和我可以编译一个类似的文件,所以为什么我有这个问题? 的代码是:

import java.util.Comparator; 
import org.junit.Assert.assertArrayEquals; 
import org.junit.Assert.assertEquals; 
import org.junit.Assert.assertFalse; 
import org.junit.Assert.assertTrue; 
import org.junit.Before; 
import org.junit.Test; 

    public class SortingTests { 

     class IntegerComparator implements Comparator<Integer> { 
     @Override 
     public int compare(Integer i1, Integer i2) { 
      return i1.compareTo(i2); 
     } 
     } 

     private Integer i1,i2,i3; 
     private OrderedArray<Integer> orderedArray; 

     @Before 
     public void createOrderedArray(){ 
     i1 = -12; 
     i2 = 0; 
     i3 = 4; 
     orderedArray = new OrderedArray<>(new IntegerComparator()); 
     } 

     @Test 
     public void testIsEmpty_zeroEl(){ 
     assertTrue(orderedArray.isEmpty()); 
     } 

     @Test 
     public void testIsEmpty_oneEl() throws Exception{ 
     orderedArray.add(i1); 
     assertFalse(orderedArray.isEmpty()); 
     } 


     @Test 
     public void testSize_zeroEl() throws Exception{ 
     assertEquals(0,orderedArray.size()); 
     } 

    } 
+1

方法大概的jar不在类路径中。你能确认吗?还请告诉你使用哪个罐子? – DNAj

+0

我正在使用JUnit 4.12,该jar应该在类路径中。我可以在同一个文件夹中编译类似的测试。 – Leo

+0

好的,我在classpath中犯了一个错误。谢谢您的帮助。 – Leo

回答

1

您应该添加关键字static将其导入。举个例子:

import static org.junit.Assert.assertFalse; 
+0

Addind关键字给我以下错误:包org.junit不存在 – Leo

3

假设你已经在classpath中JUnit dependency,使用import static的断言方法:

import static org.junit.Assert.assertArrayEquals; 
import static org.junit.Assert.assertEquals; 
import static org.junit.Assert.assertFalse; 
import static org.junit.Assert.assertTrue; 

或者干脆使用:

import static org.junit.Assert.*; 
+0

好的,我在classpath中犯了一个错误。无论如何,感谢您的帮助。 – Leo

1

你在找什么是一个静态导入

线import org.junit.Assert.assertArrayEquals;从类org.junit.Assert

引用的方法assertArrayEquals导入一个静态方法,所以它是可调用就像assertEquals(0,orderedArray.size());与静态导入线来完成。请尝试以下:

import static org.junit.Assert.assertArrayEquals; 
import static org.junit.Assert.assertEquals; 
import static org.junit.Assert.assertFalse; 
import static org.junit.Assert.assertTrue; 

另外,您可以:

import static org.junit.Assert.*; 

,或者你可以:

import org.junit.Assert; 

和引用类似

Assert.assertEquals(0,orderedArray.size());