How to check if two boolean values are equal?

寵の児 提交于 2019-12-07 05:54:12

问题


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:

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.


回答1:


The == operator works with booleans.

boolean isEqual = (bool1 == bool2);

(The parentheses are unnecessary, but help make it easier to read.)




回答2:


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)));
    }
}



回答3:


You can use logical expression

boolean isEqual = bool1 && bool2;


来源:https://stackoverflow.com/questions/31366231/how-to-check-if-two-boolean-values-are-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!