Skip to content
Advertisement

passing Parameterized input using Mockitos

I am using Mockito for unit testing. I am wondering if its possible to send Parametrized input parameters with as in Junit testing
e.g

JavaScript

Advertisement

Answer

In JUnit, Parameterized tests use a special runner that ensure that the test is instantiated multiple times, so each test method is called multiple times. Mockito is a tool for writing specific unit tests, so there is no built-in ability to run the same test multiple times with different Mockito expectations.

If you want your test conditions to change, your best bet is to do one of the following:

  • Parameterize your test using JUnit, with a parameter for the mock inputs you want;
  • Run a loop of different parameters in your test, which unfortunately avoids the “test one thing per method” philosophy
  • Extract a method that actually performs the test, and create a new @Test method for each mock you want.

Note that there’s no prohibition on using mock objects as @Parameterized test parameters. If you’re looking to parameterize based on mocks, you can do that, possibly creating the mock and setting the expectations in a static method on the test.


Note about runners: This Parameterized test runner conflicts with Mockito’s MockitoJUnitRunner: Each test class can only have one runner. You’ll want to switch to @Before and @After methods or a Mockito JUnit4 rule for your setup, if you use them both.

As an example, compressed from a different answer that explains more about Parameterized runners versus JUnit rules and lifting from the JUnit4 Parameterized Test doc page and MockitoRule doc page:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement