繁体   English   中英

JUnit如何知道要测试哪个类?

[英]How does JUnit know which class to be tested?

我有两个类Calculator1Calculator2 ,它们位于src文件夹下名为com.zzy.junit.user的包中。 我使用myeclipse创建两个测试类来分别测试它们。 当我在其中执行一个测试类时,Junit4如何知道测试哪个类?

1级

package com.zzy.junit.user;

public class Calculator1 {

    private int a;
    private int b;

    public Calculator1(int a,int b)
    {
        this.a = a;
        this.b = b;
    }

    public int add()
    {
        return a+b;
    }
}

2级

package com.zzy.junit.user;

public class Calculator2{

    public int divide(int a,int b)
    {
        return a/b;
    }
}

两个测试类如下:它们都在名为test的src文件夹中

测试类1

package com.zzy.junit.user;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;  

import org.junit.Test;

public class TestCalculator1 {

    @Test
    public void testAdd() {
        Calculator1 s = new Calculator1(3,6);
        int z = s.add();
        assertThat(z,is(9));
    }

}

测试类2

package com.zzy.junit.user;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

import org.junit.Test;

public class TestCalculator2 {

    @Test
    public void testDivide() {
        TestCalculator2 t = new TestCalculator2();
        int z = t.divide(4, 2);
        assertThat(z,is(2));
    }

}

我想知道如果我执行名为TestCalculator2的测试类,Junit4如何知道我确实想测试Calculator1类。 它与测试类的名称有关吗?

JUnit是一个用于执行可以通过或失败的测试的框架。 单个测试通常关注单个类的事实是大多数Java程序员观察到的惯例。 JUnit4不知道正在测试哪些类,它只是执行所有使用@Test注释的方法。

通常因为它的名称以“Test”结尾或因为它具有@Test注释。

根据您的(以前)发布的测试代码,该testAdd的方法TestCaculator1正在测试一种add在法StudenttestDivide的方法TestCaculator1正在测试一种divide的方法Teacher

在上次编辑时,测试类名称现在更接近于测试类的名称。

正如另一个答案中所指出的,没有真正要求测试类专门用于测试特定类,尽管人们倾向于按惯例建立一对一关系。

真正的连接是在方法级别,完全取决于测试方法实际运用的类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM