【问题标题】:Test cases won't work when implementing my own stack实现我自己的堆栈时测试用例不起作用
【发布时间】:2021-08-07 15:12:58
【问题描述】:

所以我们的作业是在我们的 won 上实现一个堆栈,然后为它编写测试用例。 这是堆栈:

    import java.util.Vector;

class Stack<T> extends Vector<T> {
    private Vector<T> stack;

    Stack() {
        stack = new Vector<T>();
    }

    // returns false or true, given the stack is empty or not.
    public boolean isEmpty() {
        return stack.size() == 0;
    }

    //returns the top element of the stack without removing it.
    public T peek() {
        return stack.get(stack.size()-1);
    }

    //puts a new element to the top of the stack
    public void push(T element) {
        stack.add(element);
    }

    //returns and removes the top element of the stack
    public T pop() {
        return stack.get(stack.size()-1);
    }
}

这是我目前的测试课。

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class StackTest {

    @Test
    void isEmpty() {
        stack s = new stack<Integer>;
        assertEquals(true, s.isEmpty());
    }

    @Test
    void peek() {
        Stack t = new Stack(1);
    }

    @Test
    void push() {
    }

    @Test
    void pop() {
    }

}

我真的很难弄清楚前两种测试方法有什么问题。其他人有想法吗?

【问题讨论】:

  • 第一种方法中,stack写成小写。在第二种方法中,您使用 int 调用 Stack 的构造函数,但未定义该构造函数。
  • 第二种测试方法并没有真正测试任何东西,它没有断言......
  • @deHaar 确保某事毫无例外地发生是一种断言。

标签: java testing junit stack


【解决方案1】:

这是错误的:

//returns and removes the top element of the stack
public T pop() {
    return stack.get(stack.size()-1);
}

你不删除元素,用remove代替get

其他错误:

void isEmpty() {
    //Typo errors here, s is uppercase and missing parenthesis
    stack s = new stack<Integer>;
    assertEquals(true, s.isEmpty());
}

@Test
void peek() {
    //What does Stack(1) mean? There is no such constructor in class
    Stack t = new Stack(1);
}

还有:

//If you already extend Vector you don't need a Vector field for the data
class Stack<T> extends Vector<T> {
    private Vector<T> stack;

【讨论】:

  • 非常感谢。这些更正很有意义。使用 Stack(1) 我试图创建一个已经有数字 1 的堆栈。但我认为 void push() { Stack t = new Stack(); t.push(1); assertEquals(假,t.isEmpty());效果更好。感谢您的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
相关资源
最近更新 更多