Java 如何检查两个布尔值是否相等?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31366231/
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
How to check if two boolean values are equal?
提问by user3541263
I need a method which I can call within the junit assertTrue()
method which compares two booleans to check if they are equal, returning a boolean value. For example, something like this:
我需要一个可以在 junitassertTrue()
方法中调用的方法,该方法比较两个布尔值以检查它们是否相等,返回一个布尔值。例如,这样的事情:
boolean isEqual = Boolean.equals(bool1, bool2);
which should return false if they are not equal, or true if they are. I've checked out the Boolean class but the only one that comes close is Boolean.compare()
which returns an int value, which I can't use.
如果它们不相等,则返回 false,如果相等则返回 true。我已经检查了 Boolean 类,但唯一接近的是Boolean.compare()
它返回一个 int 值,我不能使用它。
采纳答案by user253751
The ==
operator works with booleans.
该==
运营商可与布尔值。
boolean isEqual = (bool1 == bool2);
(The parentheses are unnecessary, but help make it easier to read.)
(括号是不必要的,但有助于使其更易于阅读。)
回答by beresfordt
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class BooleanEqualityTest {
@Test
public void equalBooleans() {
boolean boolVar1 = true;
boolean boolVar2 = true;
assertTrue(boolVar1 == boolVar2);
assertThat(boolVar1, is(equalTo(boolVar2)));
}
}