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

What is Mocking?

Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation. Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want … Read more

How to run JUnit test cases from the command line

For JUnit 5.x it’s: java -jar junit-platform-console-standalone-<version>.jar <Options> Find a brief summary at https://stackoverflow.com/a/52373592/1431016 and full details at https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher For JUnit 4.X it’s really: java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name] But if you are using JUnit 3.X note the class name is different: java -cp .:/usr/share/java/junit.jar junit.textui.TestRunner [test class name] You might need to … Read more

Mocking static methods with Mockito

Use PowerMockito on top of Mockito. Example code: @RunWith(PowerMockRunner.class) @PrepareForTest(DriverManager.class) public class Mocker { @Test public void shouldVerifyParameters() throws Exception { //given PowerMockito.mockStatic(DriverManager.class); BDDMockito.given(DriverManager.getConnection(…)).willReturn(…); //when sut.execute(); // System Under Test (sut) //then PowerMockito.verifyStatic(); DriverManager.getConnection(…); } More information: Why doesn’t Mockito mock static methods?