* BAEL-2182

* refactoring
This commit is contained in:
myluckagain 2018-09-23 08:43:20 +03:00 committed by Grzegorz Piwowarek
parent 991d6937f1
commit 5e8076dddd
2 changed files with 108 additions and 0 deletions

View File

@ -0,0 +1,70 @@
package com.baeldung.switchstatement;
public class SwitchStatement {
public String exampleOfIF(String animal) {
String result;
if (animal.equals("DOG") || animal.equals("CAT")) {
result = "domestic animal";
} else if (animal.equals("TIGER")) {
result = "wild animal";
} else {
result = "unknown animal";
}
return result;
}
public String exampleOfSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
case "CAT":
result = "domestic animal";
break;
case "TIGER":
result = "wild animal";
break;
default:
result = "unknown animal";
break;
}
return result;
}
public String forgetBreakInSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
System.out.println("domestic animal");
result = "domestic animal";
default:
System.out.println("unknown animal");
result = "unknown animal";
}
return result;
}
public String constantCaseValue(String animal) {
String result = "";
final String dog = "DOG";
switch (animal) {
case dog:
result = "domestic animal";
}
return result;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.switchstatement;
import org.junit.Test;
import org.junit.Assert;
public class SwitchStatementUnitTest {
private SwitchStatement s = new SwitchStatement();
@Test
public void whenDog_thenDomesticAnimal() {
String animal = "DOG";
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
@Test
public void whenNoBreaks_thenGoThroughBlocks() {
String animal = "DOG";
Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
}
@Test(expected=NullPointerException.class)
public void whenSwitchAgumentIsNull_thenNullPointerException() {
String animal = null;
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
@Test
public void whenCompareStrings_thenByEqual() {
String animal = new String("DOG");
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
}