2015-11-23 2 views
2

У меня есть программа связанного списка, которая имитирует классы String и StringBuilder - программа компилируется и работает нормально, проблема возникает при ее тестировании в Юнит.JUnit: expected <java.lang.IndexOutOfBoundsException> но был <java.lang.NullPointerException>

Неудачи: 1) t33bTestIndexOutOfBoundsCharAtLength0 java.lang.Exception: Неожиданное исключение, как ожидается, но был

2) t34bTestIndexOutOfBoundsSetCharAtLength0 java.lang.Exception: Неожиданное исключение, как ожидается, но был ... 2 более

Так что я не уверен, откуда приходит NullPointerException.

Вот мой код:

//Relevant Junit tests  

    @Test(expected=IndexOutOfBoundsException.class) 
    public void t33bTestIndexOutOfBoundsCharAtLength() { 
    LString testLString = new LString(testString); 
    System.out.println(testString.length()); 
    testLString.charAt(testString.length()); 
    } 

    @Test(expected=IndexOutOfBoundsException.class) 
    public void t34bTestIndexOutOfBoundsSetCharAtLength() { 
    LString testLString = new LString(testString); 
    testLString.setCharAt(testString.length(), newChar); 
    } 

Более

import java.io.*; 
import java.util.Arrays;`` 


public class LString{ 

    /*--------------------------- node class ------------------------*/ 
    public class node{ 
       public char c; 
       public node next; 

       /*--- node constructors ---*/  
       public node(){ 
       }//end 

       public node(char ch){ 
       c = ch; 
      next = null;   
       }//end    

      public node(char dt, node obj){ 
       c = dt; 
       next = obj.next; 
      }//end  

      public String toString(){ 
       return c + ""; 
      } //end 


      public void setChar(char ch){ 
       this.c=ch; 
      } 

      public char getChar(){ 
       return this.c; 
      } 

    } 
    /*----------------------- end node class ------------------------*/   

/*------ fields --------*/ 
    private node front = null; 
    private int counter=0; 

/*---- constructors -----*/ 
    public LString(){      
    }//end 


    public LString(String str){  

     for(int i =0; i < str.length(); i++){ this.append(str.charAt(i)); } 
    }//end 


/*------- methods -------*/ 

    public int length(){ 
     return counter; 
    }//end length 


    public boolean inBounds(int index){ 
     if(index < 0 || index > counter) return false; 
     else return true; 
    }//end inBounds  


    private void append(char ch){ 
      if (front == null) { front = new node(ch); }//nothing follows 
     else { 
       node curr = front; 
       while (curr.next != null) { curr = curr.next; } 
       curr.next = new node(ch);    
     } 
     counter++; 
    }//end append 


    public char charAt(int idx){   
     if ((inBounds(idx)==false) || idx< 0) throw new IndexOutOfBoundsException(""); 
     else{ 
      if(front == null) return front.getChar();    
      node curr = this.front; 
      for(int i =0; i< idx; i++){ 
        curr = curr.next;      
      }  

      return curr.getChar(); 
     }   
    }//end charAt 


    public void setCharAt(int idx, char ch){ 
     node curr = front; 

     if (!(inBounds(idx)) || idx < 0 ) throw new IndexOutOfBoundsException(""); 
     else{  for(int i =0; i< idx; i++){ curr = curr.next; }  

     } 

     curr.setChar(ch);     
    }//end setCharAt  


    public String toString() { 
     StringBuilder str = new StringBuilder(); 

     node curr = front; 
     while (curr != null) { 
      str.append(curr.toString()); 
      curr = curr.next; 
     } 
     return str.toString(); 
    }//end toString 


    @Override 
    public boolean equals(Object other){ 
     if (other == null || !(other instanceof LString)) return false;  
     else{ 
      LString nother = (LString) other; 
      return ( Arrays.equals(this.toString().toCharArray(), nother.toString().toCharArray() ) ); 
     } 
    }//end equals 


    public LString substring(int start, int end){ 
     if(!(inBounds(start)) || !(inBounds (end))) throw new IndexOutOfBoundsException(""); 
     if(start == end || this.length() ==0) return (new LString()); 
     else{ 
      String sub = "";  
      for(int i =start; i <= (end -1); i++){ sub += String.valueOf( this.charAt(i) ); } 

      return (new LString(sub));   
     } 
    }//end substring 


    public int compareTo(LString other){ 

     if(Arrays.equals(this.toString().toCharArray(), other.toString().toCharArray()) ) return 0; 
     else if((other.length() != this.length()) ) return (this.length() - other.length()); 
     else{ 
      int lexic=0; 

      node thisCurr = front;    
      node otherCurr = other.front; 

      for(int i =0; i < this.length(); i++){ 
        if(thisCurr.c != otherCurr.c) lexic += ( ((int)thisCurr.c) - ((int)otherCurr.c) ); 
        thisCurr = thisCurr.next; 
        otherCurr = otherCurr.next; 
      } 
      return lexic; 
     } 
    }//end compareTo 


    public LString replace(int start, int end, LString lstr){ 

     if(!(inBounds(start)) || !(inBounds(end)) || end < start) throw new IndexOutOfBoundsException(""); 
     else{ 
       if (start == end) return ( new LString(this.substring(0, start) + lstr.toString() + this.substring(end, this.length()) ) ); 
       if (start == end || end == this.length()) return ( new LString(this.toString() + lstr.toString() ) ); 
       else return ( new LString(this.substring(0, start) + lstr.toString() + this.substring(end, this.length())) ); 
     }  
    }//end replace    
} 
/***************** end LString class ***************/ 
+3

Проверьте свой стек, он должен точно указать, где это произошло. –

+1

Можете ли вы разместить свой тестовый код? – Hua

+0

вы используете this.length(). Я думаю, что где-то ваше значение становится нулевым. проверьте консоль на трассировку стека. вставьте его здесь –

ответ

1

Что такое значение testString, что вы используете в своих 2 тестов? Если они null, вы получите NullPointerException в конструкторе LString.

Смежные вопросы