Java 如何使用assertTrue?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25352329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:10:54  来源:igfitidea点击:

How to use assertTrue?

javaeclipsejunit

提问by darlik

I have:

我有:

package com.darlik.test;

import org.junit.Assert;

public class Test {

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

}

package with org.junit is set and working but in line with assertTrue i have error:

带有 org.junit 的包已设置并正常工作,但与 assertTrue 一致,我有错误:

The method assertTrue(int, int) is undefined for the type Test

未定义类型 Test 的方法 assertTrue(int, int)

Why? I use Eclipse.

为什么?我使用 Eclipse。

采纳答案by Reimeus

assertTrueis based on a single boolean condition. For example

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

assertTrue(1 == 2);

You need to import the statement statically to use

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

import static org.junit.Assert.assertTrue;

Typically, however assertEqualsis used when comparing 2 parameters, e.g.

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

public class MyTest {

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

回答by m4rtin

From the doc : assertTrue(boolean)or assertTrue(String, boolean)if you want to add a message.

从文档:assertTrue(boolean)assertTrue(String, boolean)如果你想添加一条消息。

AssertTrue assert that a conditionis true, you still have to code such condition for it to be evaluatedat runtime.

AssertTrue 断言某个条件为真,您仍然必须编写此类条件以便在运行时对其进行评估

回答by Jeroen Vannevel

You have to specify the class that defines that method:

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

Assert.assertTrue(condition);

Furthermore you're calling the method with 2 parameters which makes no sense. assertTrueexpects a single boolean expression.

此外,您正在使用 2 个参数调用该方法,这是没有意义的。assertTrue需要一个布尔表达式。

Although you can also do this by using a static import:

虽然您也可以通过使用静态导入来做到这一点:

import static org.junit.Assert.*;

which will allow you to call it as assertTrue(condition);instead.

这将允许您改为调用它assertTrue(condition);

回答by Prakash

Better try assertThat with matchers. Check this blog about it https://objectpartners.com/2013/09/18/the-benefits-of-using-assertthat-over-other-assert-methods-in-unit-tests/

最好用匹配器尝试 assertThat 。检查这个博客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)));
}