У меня возникают проблемы при прохождении моего NullPointerException
теста.
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class MyCustomStringTest {
private MyCustomStringInterface mycustomstring;
@Before
public void setUp() {
mycustomstring = new MyCustomString();
}
@After
public void tearDown() {
mycustomstring = null;
}
// Test if a null point exception is thrown
@Test(expected = NullPointerException.class)
public void testCountNumbers2() {
mycustomstring.setString(null);
assertNull(mycustomstring.countNumbers());
}
}
Этот тест не проходит, даже если я проверяю, что он не нулевой.Вот реализация для mycustomstring
и countNumbers()
.
public class MyCustomString implements MyCustomStringInterface {
private String string;
@Override
public String getString() {
return string;
}
@Override
public void setString(String string) {
this.string = string;
}
@Override
public int countNumbers() {
StringBuffer tmpString = new StringBuffer();
int count=0;
boolean inNumber=false;
//avoid null pointer exception!
if(string==null || string.isEmpty())
return 0;
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (Character.isDigit(ch)) {
if (!inNumber) {
count++;
inNumber = true;
}
}
else {
if (inNumber) {
inNumber = false;
}
}
}
return count;
}
int countNumbers();
возвращает строку, состоящую из всех символов в исходной строке, с каждым обратным сегментом n
символов.Если padded
истинно, к последнему сегменту символов будет добавлен символ 'X', достаточный для того, чтобы сделать:
* a full segment.
* <p>
* <p>
* Examples:
* - For n=2 and padded=true, the method would return the string with every pair of characters swapped in place, and
* if there were an odd number of characters, an X would be added to the last segment before it is reversed.
* - For n=3 and padded=false, the method would return the string with every segment of 3 characters reversed in place,
* and the final segment would be reversed even if less than 3 characters without any additional characters added.
* <p>
* Values n and padded are passed as parameters. The starting character is considered to be in Position 1.
*
* @param n Determines size of the string segments to be reversed
* @param padded Determines whether an incomplete final segment will be padded with 'X'.
* @return String with the segments in their original order and the contents of the segments reversed.
* @throws NullPointerException If the current string is null or uninitialized.
* @throws IllegalArgumentException If "n" less than or equal to zero, and the current string is not null.
*/