问题
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