toggle boolean (#12618)

This commit is contained in:
Kai Yuan 2022-08-21 18:43:45 +02:00 committed by GitHub
parent 94ecd00052
commit a20006b451
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package com.baeldung.toggleboolean;
public class ToggleBoolean {
public static Boolean toggle(Boolean b) {
if (b == null) {
return b;
}
return !b;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.toggleboolean;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class ToggleBooleanUnitTest {
@Test
void givenPrimitiveBoolean_whenUsingNotOperator_shouldToggleTheBoolean() {
boolean b = true;
b = !b;
assertFalse(b);
b = !b;
assertTrue(b);
}
@Test
void givenNullBoxedBoolean_whenUsingNotOperator_shouldThrowNPE() {
assertThatThrownBy(() -> {
Boolean b = null;
b = !b;
}).isInstanceOf(NullPointerException.class);
}
@Test
void givenPrimitiveBoolean_whenUsingXorOperator_shouldToggleTheBoolean() {
boolean b = true;
b ^= true;
assertFalse(b);
b ^= true;
assertTrue(b);
}
@Test
void givenBooleanObj_whenToggle_shouldGetExpectedResult() {
//boxed Boolean
Boolean b = true;
b = ToggleBoolean.toggle(b);
assertFalse(b);
b = ToggleBoolean.toggle(b);
assertTrue(b);
b = null;
b = ToggleBoolean.toggle(b);
assertNull(b);
//primitive boolean
boolean bb = true;
bb = ToggleBoolean.toggle(bb);
assertFalse(bb);
bb = ToggleBoolean.toggle(bb);
assertTrue(bb);
}
}