无法在 Junit 中覆盖测试用例?

我试图通过为Stack方法,push(),pop()和peak()编写单元测试来理解Junit和eclEmma。但他们都失败了。似乎他们都没有被覆盖。我最初以为这是我的代码在如何将整数对象推到堆栈上的语法问题,但似乎这不是问题所在。


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


import org.junit.Before;

import org.junit.jupiter.api.Test;

import java.util.Stack;


public class StackMethodTesting {

    private Stack<Integer> aStackOfInt;


    @Before

    public void initialize()

    {

        aStackOfInt = new Stack<Integer>();

        System.out.println(" a new Stack");

    }


    @Test

    public void testpush() {

        aStackOfInt.push(new Integer(1));

        assertEquals(true,aStackOfInt.peek().equals(new Integer(1)));

    }

    @ Test

    public void testPop() {

        aStackOfInt.push(22);

        assertEquals (new Integer(22),aStackOfInt.pop());

    }

    @Test

    public void testpeek()

    {

        aStackOfInt.push(222);

        assertEquals(new Integer(222),aStackOfInt.peek());

    }



}

我假设突出显示的红色代码意味着它们没有被执行。如果是这样,我不知道出了什么问题。以下是运行结果:

http://img.mukewang.com/62fcb5810001828513730945.jpg

月关宝盒
浏览 158回答 1
1回答

临摹微笑

您在测试中混合到 JUnit API,JUnit4 和 JUnit5。所以,如果你想使用最新的一个(我推荐你使用的JUnit 5),你应该从JUnit5软件包中导入所有内容:org.junit.jupiter。因此,您的测试用例将如下所示(请注意,我还进行了一些其他更改):import static org.junit.jupiter.api.Assertions.*;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import java.util.Stack;class StackMethodTesting {&nbsp; &nbsp; private Stack<Integer> aStackOfInt;&nbsp; &nbsp; @BeforeEach&nbsp; &nbsp; void initialize()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; aStackOfInt = new Stack<Integer>();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" a new Stack");&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; void testpush() {&nbsp; &nbsp; &nbsp; &nbsp; Integer value = new Integer(1);&nbsp; &nbsp; &nbsp; &nbsp; aStackOfInt.push(value);&nbsp; &nbsp; &nbsp; &nbsp; assertTrue(aStackOfInt.peek().equals(value));&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; void testPop() {&nbsp; &nbsp; &nbsp; &nbsp; Integer value = new Integer(22);&nbsp; &nbsp; &nbsp; &nbsp; aStackOfInt.push(value);&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(value, aStackOfInt.pop());&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; void testpeek()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Integer value = new Integer(222);&nbsp; &nbsp; &nbsp; &nbsp; aStackOfInt.push(value);&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(value, aStackOfInt.peek());&nbsp; &nbsp; }}您可以在此处阅读有关 JUnit5 的更多信息,https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java