11

I have a method and wish to test it with different values. My question is: how can I write a JUnit test that would test the same method with different values?

Mark W
  • 5,824
  • 15
  • 59
  • 97
user722781
  • 121
  • 1
  • 1
  • 3

3 Answers3

9

You can take a look at parametrized tests like in example.

You can also use theories which is more convenient in a lot of cases.

Ajak6
  • 727
  • 5
  • 17
Constantiner
  • 14,231
  • 4
  • 27
  • 34
  • 3
    Theories seem a lot cleaner/better than parameterized tests, at least in implementation. But it's too bad that JUnit doesn't have anything as clean as NUnit's `[TestCase]` annotation that lets you specify per test method. – Allan Apr 08 '13 at 19:35
  • Here's a good article about Parametrized: [How to Create JUnit Parameterized Tests](https://blog.parasoft.com/how-to-create-junit-parameterized-tests-faster) – ajaristi Sep 30 '19 at 21:40
5

JUnit4 supports parameterized tests for just this purpose.

See this tutorial.

skaffman
  • 398,947
  • 96
  • 818
  • 769
-2

I suggest you create a different unit test for each one of your (overloaded) function definitions, because arguably you are testing in fact different functions. For instance:

class MainClass {
public void method( int param) {... }
public void method( String param) { ...}
}

class MainClassTest {
@Test
public void methodIntTest() {
 //call method(int)
}

@Test
public void methodStringTest() {
 //call method(String)
}
}
Liv
  • 6,006
  • 1
  • 22
  • 29
  • Not if what OP wants is two calls to the same method with different arguments, which is how I read his question. He says he has "a method". In that case, of course, you can still write different tests, named for the condition being tested. – CPerkins Apr 26 '11 at 17:47
  • ok, my understanding of the question seems to be wrong then. apologies to all on this channel, i thought he meant his function accepts different arguments (i.e. overloading) -- hence the above solution. – Liv Apr 26 '11 at 17:51
  • No apologies needed. I think your basic suggestion is still valid, reworded to address differently-named tests for a set of calls with different values to the same method. – CPerkins Apr 26 '11 at 19:39
  • Liv might want to delete this answer since we all now agree that it does not answer the poster's question (if it will allow you to with this many comments, I'm posting this instead of downvoting) – Sled Oct 03 '11 at 18:51
  • sorry i have been offline for quite a while -- so do we agree I need to delete the answer then? I don't mind doing so if this was wrong -- just obviously been out of the loop for a while and want to make sure I got the right idea here.thanks. – Liv Oct 06 '11 at 07:40