Skip to content
Tim Tong edited this page Aug 2, 2015 · 12 revisions

Frameworks

  • JUnit
  • Mockito
  • PowerMockito

*** Should only be using mock objects and mocked behavior for unit testing.

JUnit

The most typical JUnit commands will be:

  • Assert.assertEquals(Object expected, Object actual);
  • Assert.assertTrue(boolean expression);
  • Assert.assertFalse(boolean expression);
  • Assert.assertNull(Object object);
  • Assert.assertNotNull(Object object);

See JUnit API for more.

To create a test:

public class SomeTestClass {
    @Test
    public void test() {
    }
}

Mockito

To create a mock object:

@RunWith(MockitoJUnitRunner.class)
public class SomeTestClass {
    @Mock
    private Object object;
}

To inject a mock object into an autowired member variable:

@RunWith(MockitoJUnitRunner.class)
public class SomeTestclass {
    @Mock
    private Object object;

    @InjectMocks
    private ClassToBeInjected myObject;
}

To mock behavior:

@Test
public void test() {
    Mockito.when(object.method(parameters)).thenReturn(returnObjectOrValue);
}

To verify if an object called a method:

@Test
public void test() {
   ...
   Mockito.verify(object).method(parameters);
}

Power Mockito

For heavy lifting mocking.

For static methods:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStaticMethod.class)
public class SomeTestClass {
    @Test
    public void test() {
        PowerMockito.mockStatic(ClassWithStaticMethod.class);

        Mockito.when(ClassWithStaticMethod.staticMethod(parameters)).thenReturn(returnValue);
    }
}

For Final Classes:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUsingTheFinalClass.class)
public class SomeTestClass {
    @Mock
    private SomeFinalClass foo;

    @Test
    public void test() {
        Mockito.when(foo.method(parameter)).thenReturn(returnValue);
    }
}

For Local Instantiations:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToBeInstantiated.class)
public class SomeTestClass {
    @Mock
    private ClassToBeInstantiated foo;

    @Test
    public void test() {
        // Instantiate only when method to be tested has call signature
        // foo = new ClassToBeInstantiated(arg1, arg2);
        PowerMockito.whenNew(ClassToBeInstantiated.class).withArguments(arg1, arg2).thenReturn(foo);
    }
}

Unit

Integration

Integration testing is temporarily put on hold.

Clone this wiki locally