Merge pull request #622 from eugenp/grzegorz_string_to_int

Add code examples for String to int mini-article
This commit is contained in:
Alex Theedom 2016-08-22 18:27:33 +01:00 committed by GitHub
commit f1516e0188
1 changed files with 63 additions and 0 deletions

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