在 Junit 中测试对象数组,但无法解析导入

Testing an array of object in Junit, but import can not be resolved

我正在尝试测试我的 insert 功能是否有效。但是 Eclipse 给我一个导入错误。我的构建路径中有 junit4。

这是我的解决方案class

public class Solution {

    public class Interval {
        int start;
        int end;
        Interval() { start = 0; end = 0; };
        Interval(int s, int e) { start = s; end = e; };
    }

    public static ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        // more code

这是我的解决方案测试class

import Solution.Interval; // Error: The import Solution can't be resolved

public class SolutionTest {
    @Before
    public void setUp() {
        ArrayList<Interval> er = new ArrayList<Interval>(); //imoprt Interval
        System.out.println("Start");
    }

删除导入语句 //导入Solution.Interval;

并尝试如下

ArrayList er = new ArrayList();

解决了我自己的问题。我将 Interval class 分成它自己的 class。这解决了问题。

所以代替:

public class Solution {

    private static class Interval {
        int start;
        int end;
        Interval() { start = 0; end = 0; };
        Interval(int s, int e) { start = s; end = e; };
    }

我这样做了:

public class Solution {
    // some code here
}

class Interval {
    int start;
    int end;
    Interval() { start = 0; end = 0; };
    Interval(int s, int e) { start = s; end = e; };
}

我认为问题是 Interval 是一个嵌套的 class,您不能在 Junit 中直接测试嵌套的 class。但如果有人知道更详细的解释,请分享。

我怀疑如果您将您的代码放在默认包以外的包中,问题就会消失。编译器可能认为 Solution 是一个包,在 Solution 包中找不到名为 Interval 的 class 或接口。

此外,如果您希望能够在没有 Solution 的情况下创建 IntervalInterval 从内部 class 更改为嵌套class:

package solution;

public class Solution {

    public static class Interval {
        private final int start;
        private final int end;

        public Interval() {
          this(0, 0);
        }

        public Interval(int start, int end) {
          this.start = start;
          this.end = end;
        }

        ...
    }

    public static ArrayList<Interval> insert(List<Interval> intervals, Interval newInterval) {
      ...
    }
}

上面的class会在"src/solution/Solution.java"

这是测试:

package solution;

import solution.Solution.Interval;

@RunWith(JUnit4.class)
public class SolutionTest {
  private final List<Interval> emptyIntervalList = new ArrayList<Interval>();

  ...
}

当然,您可以将 Interval 设为顶级 class,但如果您这样做,我强烈建议您将其放在不同的文件中(名为 Interval.java)。

我也推荐使用 the standard Maven directory layout