【问题标题】:Junit test of a class requires objects of other classes一个类的Junit测试需要其他类的对象
【发布时间】:2020-07-08 07:49:55
【问题描述】:

我有一个这样定义的类:

public class Monster {
    public static final int ARENA_SIZE = 480;

    public int health; //can be negative since it will then be removed
    public int speed;
    public int counter;
    public int x; //current position
    public int y; //current position
    public mapObject next;
    public void nextAlgorithm(mapObject[][] map) {
        aNode[][] aNodeMap = newANodeMap(map); //1. create a new aNodeMap

        PriorityQueue<aNode> pq = newPriorityMap(aNodeMap[this.x][this.y]); //2. create a new priority queue with starting point added
        aNode current;

        while (pq.isEmpty() == false) {
            current = pq.poll();
            if (endPointReached(current.x, current.y)) //3. Is the end point reached?
                break;
            aNode[] neighbours = findNeighbour(current.x, current.y, aNodeMap); //4. The end point isn't reached, find me the neigbours
            for (aNode neighbour : neighbours) //5. process all my neighbours
                processNeighbour(current, neighbour, pq);
        }
        next = updateNext(aNodeMap[ARENA_SIZE - 1][ARENA_SIZE - 1], this.x, this.y); //6. Update my next after all these work
    }

简单来说,有一个算法需要其他类的输入,mapObject,也是我自己写的另一个包。

我的问题是,除了

import MapObject.*;

在 junit 中,我可以在其中初始化一个夹具

@Before

有没有更好的方法?

【问题讨论】:

  • 它如何需要mapObject 类的对象?看起来它创建了一个(newANodeMap.
  • 在 nextAlgorithm 的函数签名中,需要一个 mapObject[][] 来进行复制。因此,它需要一个 mapObject 类的对象。其次,它创建一个 newANodeMap 是事实,假设它需要一个 mapObject[][] 对象来复制。因此,我需要在测试用例中使用 mapObject。请问我应该修改问题的哪一部分以使其他人更清楚?

标签: java intellij-idea junit


【解决方案1】:

在测试用例本身而不是在@Before 方法中创建输入对象(即mapObject[][])可能更好。这允许您使用不同的输入对象创建多个测试用例。

@Test void testWithSpecificArrayConfiguration1() {
    mapObject[][] objectConfig1 = createConfig1();
    testMonster.nextAlgorith(objectConfig1);
    // verification steps for config 1
}
@Test void testWithSpecificArrayConfiguration2() {
    mapObject[][] objectConfig2 = createConfig2();
    testMonster.nextAlgorith(objectConfig2);
    // verification steps for config 2
}

请注意,输入是mapObject 感觉不对,但实际算法适用于aNode[][];但是如果不知道代码的上下文就很难判断。

【讨论】:

  • 谢谢,我会在帖子上更新关于 newANode 问题的信息。由于我是JUnit新手,在测试这个类的时候导入其他类的自写包是正常的吗?如果没有,JUnit 是否提供了任何方法来执行此功能,即在当前测试单元中导入与当前类不同的类。
  • @AndesLam 单元测试总是需要包含被测试类中包含的所有类。如果您觉得某个导入有问题,您可以通过为它引入一个接口来从包含的类中抽象出来,因此您只需要导入该接口。这通常会产生更好的代码,因为您是针对抽象而不是实现编写代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 2014-07-02
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
相关资源
最近更新 更多