如何为CompareTo创建JUnit测试?

时间:2013-09-23 03:15:20

标签: java compareto

我是编程的新手,我做了一个compareTo方法,我想创建一个测试,看它是否有效,但我不知道如何。

2 个答案:

答案 0 :(得分:0)

总而言之,您需要对JUnit有基本的了解。 以下是一个简单的JUnit测试,但请参阅this blog post以获取详细说明。祝你好运!

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        // Run once before any method in this class.
    }

    @Before
    public void setUp() throws Exception {
        // Runs once before each method annotated with @Test
    }

    @Test
    public void testSomething() {
        // The Sample Test case
        fail("Not yet implemented");
    }

    @Test
    public void testAnotherThing() {
        // Another Sample Test case
        Me me = new Me();
        assertEquals("cmd", me.getFirstName());
    }

    @After
    public void tearDown() throws Exception {
        // Runs once after each method annotated with @Test.
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        // Run once after all test cases are run
    }

}

答案 1 :(得分:-1)

首先创建一个junit测试类(右键单击时应该在选项中,它不是“Class”)

默认情况下你会得到一个方法,

public void test(){
fail("blah blah");
}

test是一个方法名称,它无关紧要,所以随意根据需要进行更改。

fail是org.junit包中的一个方法,你不想在那里失败,因为它会自动失败你要测试的任何东西,所以暂时删除它

现在我假设compareTo方法返回负数或零或正数。

所以你可能想先测试它是否返回一个值。

http://junit.sourceforge.net/javadoc/org/junit/Assert.html列出了可用于测试的方法。)

从列表中,我看到assertNotNull通过您的方法检查返回值。如果方法正确工作,它将返回一个值(测试成功),但如果没有,则会抛出异常(测试失败)。

@Test
public void test() {
    org.junit.Assert.assertNotNull(yourpackage.yourclass.yourmethod(if static));

}   

import yourpackage.yourclassname;
@Test
public void test() {
            yourclassname test = new yourclassname();
    org.junit.Assert.assertNotNull(test.compareTo());

}   

但是如果你在同一个包中有junit测试类的类,则不需要进行任何导入。

希望有所帮助

相关问题