Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "right" way to test the output of Java methods?

In Python, I often have tests which look something like this:

tests = [
    (2, 4),
    (3, 9),
    (10, 100),
]
for (input, expected_output) in tests:
    assert f(input) == expected_output

What is the "right" way to write tests like this (where a set of test cases is specified, then a loop runs each of them) in Java with JUnit?

Thanks!

Preemptive response: I realize I could do something like:

assertEquals(4, f(2))
assertEquals(9, f(3))
....

But... I'm hoping there is a better way.

like image 490
David Wolever Avatar asked Mar 19 '09 16:03

David Wolever


People also ask

How do you test methods in Java?

write a main method on your class, and call your test method. To check by running just write a main method and call this method with arguments. If you want to have a test case, take a look at JUnit or Mokito to write a test. There should be a way to run parts or the code without writing a main method or a test-class.

How do you test your code in Java?

Right click on the Test project, then select New > JUnit Test Case. Name the Test case DogTest, then click on O.K. Eclipse would generate some boilerplate code for us. To run your test, right click anywhere on the code editor and select Run As > JUnit Test. If you did everything correctly, your test should run!

What does test () do in Java?

The test code is written to verify that the application works the way you want it to. Test cases must be run once they've been written to ensure the code works when the results are checked. With test-driven development, the unit test must be written and executed before any code is written.

How do you check if a method is called in Java?

While you can replace it with blank == true , which will work fine, it's unnecessary to use the == operator at all. Instead, use if (blank) to check if it is true, and if (! blank) to check if it is false.


1 Answers

Same thing.

    int[][] tests = {
            {2, 4},
            {3, 9},
            {10, 100}
    };
    for (int[] test : tests) {
        assertEquals(test[1], f(test[0]));
    }

Certainly not as pretty as python but few things are.

You may also want to look into JUnit Theories, a future feature...

like image 74
Nick Veys Avatar answered Sep 24 '22 19:09

Nick Veys