Skip to content

Commit d26bdb7

Browse files
author
Grzegorz Piwowarek
committed
Add code examples for String to int mini-article
1 parent fb5cc7d commit d26bdb7

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung;
2+
3+
import org.junit.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
7+
public class StringToIntTest {
8+
9+
@Test
10+
public void givenString_shouldConvertToInt1() throws Exception {
11+
String givenString = "42";
12+
13+
int result = Integer.parseInt(givenString);
14+
15+
assertThat(result).isEqualTo(42);
16+
}
17+
18+
19+
@Test
20+
public void givenString_shouldConvertToInt2() throws Exception {
21+
String givenString = "42";
22+
23+
Integer result = Integer.valueOf(givenString);
24+
25+
assertThat(result).isEqualTo(42);
26+
}
27+
28+
@Test
29+
public void givenString_shouldConvertToInt3() throws Exception {
30+
String givenString = "42";
31+
32+
Integer result = new Integer(givenString);
33+
34+
assertThat(result).isEqualTo(42);
35+
}
36+
37+
@Test
38+
public void givenString_shouldConvertToInt4() throws Exception {
39+
String givenString = "42";
40+
41+
int result = Integer.decode(givenString);
42+
43+
assertThat(result).isEqualTo(42);
44+
}
45+
46+
@Test(expected = NumberFormatException.class)
47+
public void givenInvalidInput_shouldThrow() throws Exception {
48+
String givenString = "nan";
49+
50+
int result = Integer.parseInt(givenString);
51+
}
52+
53+
}

0 commit comments

Comments
 (0)