如何使用assertTrue?

时间:2014-08-17 18:30:02

标签: java eclipse junit

我有:

package com.darlik.test;

import org.junit.Assert;

public class Test {

    public static void main(String[] args) {
        assertTrue(1, 2);
    }

}
带有org.junit的

包已设置并正常工作但与assertTrue一致我有错误:

  

对于类型Test

,方法assertTrue(int,int)未定义

为什么呢?我使用Eclipse。

5 个答案:

答案 0 :(得分:11)

assertTrue基于单个布尔条件。例如

assertTrue(1 == 2);

您需要静态导入语句才能使用

import static org.junit.Assert.assertTrue;

通常,在比较2个参数时使用assertEquals,例如

public class MyTest {

   @Test
   public void testAssert() throws Exception {
        assertEquals(1, 2);
   }
}

答案 1 :(得分:6)

您必须指定定义该方法的类:

Assert.assertTrue(condition);

此外,你用2个参数调用方法是没有意义的。 assertTrue需要一个布尔表达式。

虽然您也可以使用静态导入来执行此操作:

import static org.junit.Assert.*;

允许您将其称为assertTrue(condition);

答案 2 :(得分:5)

如果您要添加消息,请从文档:assertTrue(boolean)assertTrue(String, boolean)

AssertTrue断言条件为真,您仍然需要编写这样的条件,以便在运行时评估

答案 3 :(得分:0)

最好用匹配器尝试断言。查看此博客https://objectpartners.com/2013/09/18/the-benefits-of-using-assertthat-over-other-assert-methods-in-unit-tests/

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

....

    @Test
    public void testNum() {
       assertThat(repo.getNum(), is(equalTo(111)));
}

答案 4 :(得分:-1)

如果项目中有 module-info.java 文件,请删除它。它不是必需的,只有在您使用 Java 的内置模块系统时才使用。