我有一個接口和一個實現(xiàn)它的類。我 @Override 該方法,我想使用 JUnit4 對其進行測試。我不知道我的方法是否有錯誤,或者我的測試課是否做錯了什么。擁有接口本身的實例是否正確,或者我應該將其設為實現(xiàn)接口的 myCustomString 類的實例。如果有人能解釋這些對象是如何相互調用的,那就太棒了。我的 JUnit 測試返回一個空指針異常。public interface MyCustomStringInterface { int countNumbers();}public class MyCustomString implements MyCustomStringInterface { private String string; @Override public int countNumbers() { while (string.length() != 0 ) { int count = 0; for (int i = 0; i < string.length(); i++) { if(Character.isDigit(string.charAt(i))) count++; } return count; } return 0;}public class MyCustomStringTest { private MyCustomStringInterface mycustomstring; @Test public void testCountNumbers1() { mycustomstring.setString("th1s strin8 shou1d hav3 numb3rs, righ7?"); assertEquals(6, mycustomstring.countNumbers()); } }
1 回答

侃侃爾雅
TA貢獻1801條經(jīng)驗 獲得超16個贊
好吧,根據(jù)您發(fā)布的代碼,您沒有創(chuàng)建MyCustomString對象。這可能是你的NullPointerException.
嘗試mycustomstring = new MyCustomString()在您的 setString 方法上方添加,如下所示:
public class MyCustomStringTest {
private MyCustomStringInterface mycustomstring;
@Test
public void testCountNumbers1() {
mycustomstring = new MyCustomString();
mycustomstring.setString("th1s strin8 shou1d hav3 numb3rs, righ7?");
assertEquals(6, mycustomstring.countNumbers());
}
}
添加回答
舉報
0/150
提交
取消