Главная страница Случайная страница КАТЕГОРИИ: АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника |
Часть 5 — Написание тестов
• Все фукции вашего класса должны быть покрыты тестами. • Использовать фикстуры для инициализации начального состояния объекта. • Итого, должно быть несколько тестовых классов, в каждом из которых целе- вая структура данных создается в фикстуре в некотором инициализированном состоянии (пустая, заполненная и тд), а после очищается. • Написать тестовый набор, запускающий все тесты.
Структура проекта:
Код программы: package queue;
/** * The < tt> Queue< /tt> class represents a first-in-first-out (FIFO) queue of * generic items. It supports the usual < em> enqueue< /em> and < em> dequeue< /em> * operations, along with methods for peeking at the top item, testing if the * queue is empty, and iterating through the items in FIFO order. */
public class Queue< Item> { private int N; // number of elements on queue private Node first; // beginning of queue private Node last; // end of queue
// helper linked list class private class Node { private Item item; private Node next; }
/** * Create an empty queue. */ public Queue() { first = null; last = null; N = 0; assert check(); }
/** * Is the queue empty? */ public boolean isEmpty() { boolean isEmpt=false; if(first==null || last==null){ isEmpt=true; } return isEmpt; }
/** * Return the number of items in the queue. */ public int size() { return N; }
/** * Return the item least recently added to the queue. * * @throws java.util.NoSuchElementException if queue is empty. */ public Item peek()throws NullPointerException{ // FIXME throw exception if queue is Empty.+ // TODO implement method+ if(first==null){ throw new NullPointerException(" Queue is empty"); } return last.item; }
/** * Add the item to the queue. */ public void enqueue(Item item)throws NullPointerException { if(item==null){ throw new NullPointerException(" Item velue null"); } Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; ++N; if (isEmpty()) { last = first; }else{
last.next=null;
} assert check(); }
/** * Remove and return the item on the queue least recently added. * * @throws java.util.NoSuchElementException if queue is empty. */ public Item dequeue(){ // FIXME throw exception if queue is Empty.+ if(N==1) { Item lastItem = first.item; first = null; last = null; --N; return lastItem; }else if(N==0){
throw new NullPointerException(" Queue is empty");
}else{ Item item = last.item; for (Node x = first; x.next! = null; x=x.next) { if(x.next.next==null){ last=x; last.next=null; break; } }
--N; if (isEmpty()) { last = null; // to avoid loitering } assert check(); return item; }
}
/** * Return string representation. */ public String toString() { StringBuilder s = new StringBuilder(); for (Node x = first; x == null; x = x.next) { s.append(x.item + " "); }
return s.toString(); }
// check internal invariants private boolean check() { if (N == 0) { if (first! = null) { return false; } if (last! = null) { return false; } } else if (N == 1) { if (first == null || last == null) { return false; } if (first! = last) { return false; } if (first.next! = null) { return false; } } else { if (first == last) { return false; } if (first.next == null) { return false; } if (last.next! = null) { return false; }
// check internal consistency of instance variable N int numberOfNodes = 0; for (Node x = first; x! = null; x = x.next) { numberOfNodes++; } if (numberOfNodes! = N) { return false; }
// check internal consistency of instance variable last Node lastNode = first; while (lastNode.next! = null) { lastNode = lastNode.next; } if (last! = lastNode) { return false; } }
return true; } }
package queue;
import java.util.Scanner;
public class QueueClient {
/** * A test client. */
public static void main(String[] args) {
Queue< String> q = new Queue< String> ();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) { String item = scanner.next(); if(item.equals(" peek")){ System.out.println(" head queue: " +q.peek()); }else{ if(item.equals(" cancel")){ break; }else{ if (! item.equals(" -")) { q.enqueue(item); } else if (! q.isEmpty()) { System.out.println(q.dequeue() + " ");
} } } } System.out.println(q.size()); } }
package queue;
import org.junit.runner.RunWith; import org.junit.runners.Suite;
/** * Created by piratXus on 02.11.2016. */
@RunWith(Suite.class) @Suite.SuiteClasses({ QueueEmptiTest.class, QueueTest.class
})
public class QueueMainTest { }
package queue;
import org.junit.Test;
/** * Created by piratXus on 02.11.2016. */ public class QueueEmptiTest { Queue< String> queue=new Queue< > ();
@Test(expected = NullPointerException.class) public void enqueueTest(){ System.out.println(" enqueue null pointer exception test"); queue.enqueue(null); }
@Test(expected = NullPointerException.class) public void peekTest(){ System.out.println(" peek null pointer exception test"); queue.peek(); }
@Test(expected = NullPointerException.class) public void dequeueTest(){ System.out.println(" dequeue null pointer exception test"); queue.dequeue(); }
}
package queue;
import org.junit.After; import org.junit.Before; import org.junit.Test;
import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertFalse;
public class QueueTest{ Queue< String> queue=new Queue< String> ();
@Before public void setQueueBeforTest(){
queue.enqueue(" 1"); queue.enqueue(" 2"); queue.enqueue(" 3"); queue.enqueue(" 4"); queue.enqueue(" 5");
}
@After public void deleteQueueAfterTest(){
queue=null; }
@Test public void isEmptyTest(){ System.out.println(" Is EmptyTest"); assertFalse(queue.isEmpty()); System.out.println(" true"); }
@Test public void sizeTest(){ System.out.println(" Is Size Test"); assertEquals(5, queue.size()); System.out.println(" true"); }
@Test public void peekTest() { System.out.println(" Is peek Test"); assertEquals(" 1", queue.peek()); System.out.println(" true");
}
@Test(expected = NullPointerException.class) public void dequeueTest(){ System.out.println(" Is dequeue Test"); assertEquals(" 1", queue.dequeue()); assertEquals(" 2", queue.dequeue()); assertEquals(" 3", queue.dequeue()); assertEquals(" 4", queue.dequeue()); assertEquals(" 5", queue.dequeue()); queue.dequeue(); System.out.println(" true");
} }
|