How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods. For example, Mockito.doThrow(new Exception()).when(instance).methodName(); or if you want to combine it with follow-up behavior, Mockito.doThrow(new Exception()).doNothing().when(instance).methodName(); Presuming that you are looking at … Read more

How to write a Unit Test?

Define the expected and desired output for a normal case, with correct input. Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) : Write a method, and above it add the @Test annotation. In the method, run … Read more

DexIndexOverflowException Only When Running Tests

com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536 Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, … Read more

How to run test methods in specific order in JUnit4?

If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order: import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SampleTest { @Test public void testAcreate() { System.out.println(“first”); … Read more

How do you generate dynamic (parameterized) unit tests in Python?

This is called “parametrization”. There are several tools that support this approach. E.g.: pytest’s decorator parameterized The resulting code looks like this: from parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ [“foo”, “a”, “a”,], [“bar”, “a”, “b”], [“lee”, “b”, “b”], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence) … ok test_sequence_1_bar … Read more

PATH issue with pytest ‘ImportError: No module named YadaYadaYada’

Recommended approach for pytest>=7: use the pythonpath setting Recently, pytest has added a new core plugin that supports sys.path modifications via the pythonpath configuration value. The solution is thus much simpler now and doesn’t require any workarounds anymore: pyproject.toml example: [tool.pytest.ini_options] pythonpath = [ “.” ] pytest.ini example: [pytest] pythonpath = . The path entries … Read more