我无法通过我的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
为true,则在最后一个字符段中将添加足够的时间来添加字符“ 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.
*/
答案 0 :(得分:0)
您的countNumbers()
方法返回一个int
,这意味着始终返回结果。因此,当您运行时:
assertNull(mycustomstring.countNumbers());
int
值将自动装箱到Integer
,并且永远不会null
。此外,countNumbers()
永远不会抛出NullPointerException
,因此永远不会满足人们将要抛出的期望。
首先进行这些JUnit检查的原因是每次导致测试失败。