Question

I am new at programming and I made a compareTo method and I want to create a test to see if it works but I don't know how to.

Était-ce utile?

La solution 2

first create a junit test class (it should be in the option when you right click, it's not "Class")

by default you get a method,

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

test is a method name and it does not matter what it is so feel free to change it as you wish.

fail is a method from org.junit package and you don't want fail there because it will automatically fail whatever you want to test so delete it for now

now I am assuming compareTo method returns negative number or zero or positive number.

so you might want to test whether it returns a value or not first.

(http://junit.sourceforge.net/javadoc/org/junit/Assert.html lists the methods you can use for testing.)

from the list, I see that assertNotNull checks for the return value by your method. if the method correctly works, it will return a value (test succeeds) but if it doesn't, it will throw exception (test fails).

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

}   

or

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

}   

but if you have the class with the junit test class in same package, you do not need to do any import.

hope it helps

Autres conseils

All in all, you need a basic understanding of JUnit. Below is is a simple JUnit Test, but please see this blog post for a detailed explanation. Good luck!

    @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
    }

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top