Skip to content

Commit 24c144f

Browse files
committed
Add tests for null & empty strings
1 parent 0f70133 commit 24c144f

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/main/java/com/thealgorithms/stacks/InfixToPrefix.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,21 @@ private InfixToPrefix() {
1313
*
1414
* @param infixExpression the infix expression to convert
1515
* @return the prefix expression
16-
* @throws Exception if the infix expression has unbalanced brackets
16+
* @throws IllegalArgumentException if the infix expression has unbalanced brackets
17+
* @throws NullPointerException if the infix expression is null
1718
*/
18-
public static String infix2Prefix(String infixExpression) throws Exception {
19+
public static String infix2Prefix(String infixExpression) throws IllegalArgumentException {
20+
// Check for unbalanced brackets
1921
if (!BalancedBrackets.isBalanced(filterBrackets(infixExpression))) {
20-
throw new Exception("invalid expression");
22+
throw new IllegalArgumentException("invalid expression");
23+
}
24+
// Null input
25+
if (infixExpression == null) {
26+
throw new NullPointerException("null input");
27+
}
28+
// Empty string
29+
if (infixExpression.isEmpty()) {
30+
return "";
2131
}
2232
StringBuilder output = new StringBuilder();
2333
Stack<Character> stack = new Stack<>();

src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.thealgorithms.stacks;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import java.util.stream.Stream;
7+
import org.junit.jupiter.api.Test;
68
import org.junit.jupiter.params.ParameterizedTest;
79
import org.junit.jupiter.params.provider.Arguments;
810
import org.junit.jupiter.params.provider.MethodSource;
@@ -15,6 +17,18 @@ void testValidExpressions(String infix, String expectedPrefix) throws Exception
1517
assertEquals(expectedPrefix, InfixToPrefix.infix2Prefix(infix));
1618
}
1719

20+
@Test
21+
void testEmptyString() {
22+
// Assuming that an empty string returns an empty prefix or throws an exception
23+
assertEquals("", InfixToPrefix.infix2Prefix(""));
24+
}
25+
26+
@Test
27+
void testNullValue() {
28+
// Assuming that a null input throws a NullPointerException
29+
assertThrows(NullPointerException.class, () -> InfixToPrefix.infix2Prefix(null));
30+
}
31+
1832
private static Stream<Arguments> provideValidExpressions() {
1933
return Stream.of(Arguments.of("3+2", "+32"), // Simple addition
2034
Arguments.of("1+(2+3)", "+1+23"), // Parentheses

0 commit comments

Comments
 (0)