Merge pull request #622 from eugenp/grzegorz_string_to_int
Add code examples for String to int mini-article
This commit is contained in:
commit
f1516e0188
63
core-java-8/src/test/java/com/baeldung/StringToIntTest.java
Normal file
63
core-java-8/src/test/java/com/baeldung/StringToIntTest.java
Normal file
@ -0,0 +1,63 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringToIntTest {
|
||||
|
||||
@Test
|
||||
public void givenString_shouldConvertToInt1() throws Exception {
|
||||
String givenString = "42";
|
||||
|
||||
int result = Integer.parseInt(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenString_shouldConvertToInt2() throws Exception {
|
||||
String givenString = "42";
|
||||
|
||||
Integer result = Integer.valueOf(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldConvertToInt3() throws Exception {
|
||||
String givenString = "42";
|
||||
|
||||
Integer result = new Integer(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldConvertToInt4() throws Exception {
|
||||
String givenString = "42";
|
||||
|
||||
int result = Integer.decode(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldConvertToInt5() throws Exception {
|
||||
String givenString = "42";
|
||||
|
||||
Integer result = Ints.tryParse(givenString);
|
||||
|
||||
assertThat(result).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenInvalidInput_shouldThrow() throws Exception {
|
||||
String givenString = "nan";
|
||||
|
||||
int result = Integer.parseInt(givenString);
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user