Skip to content

Instantly share code, notes, and snippets.

@alifhasnain
Last active November 17, 2020 21:24
Show Gist options
  • Save alifhasnain/0b2ef5144c81c1a19ce9a4e2b74712ee to your computer and use it in GitHub Desktop.
Save alifhasnain/0b2ef5144c81c1a19ce9a4e2b74712ee to your computer and use it in GitHub Desktop.
Unit Testing Notes

Instantiate a mock object (Without Annotation)

Mockito.mock(ClassName.class);

Instantiate a mock object (With Annotation)

@RunWith(MockitoJUnitRunner.class)
public class MyTestClassTest {
	@Mock ClassName1 variableName1;
	@Mock ClassName2 variableName2;
}

Return something specific when some mock method is called

Mockito.when(mContextMock.getString(STRING_ID)).thenReturn("STRING_AS_PER_ID");
Mockito.when(someMockClassInstance.updateUsername(any(String.class), any(String.class)))
                .thenReturn(new ResultClassThatHasToBeReturned());

Call a method for a specific number of time and capture value

ArgumentCaptor<String> ac = ArgumentCaptor.forClass(String.class);
Mockito.verify(mockClassInstance, Mockito.times(2)).methodOfTheMockClass(ac.capture(), ac.capture());
List<String> captures = ac.getAllValues();
Assert.assertEquals(captures.get(0), SOME_VALUE);
Assert.assertEquals(captures.get(1), SOME_VALUE);
Assert.assertThat(captures.get(2), CoreMatchers.is(SOME_VALUE));
Assert.assertThat(captures.get(3), CoreMatchers.is(SOME_VALUE));

Compare custom class with reflection equals

ArgumentCaptor<User> acUser = ArgumentCaptor.forClass(User.class);
SUT.updateUsernameSync(USER_ID, USER_NAME);
Mockito.verify(mUserCacheMock).cacheUser(acUser.capture());
Assert.assertTrue(new ReflectionEquals(USER).matches(acUser.getValue()));

Verify if a method receives the correct value (without argument captor)

Mockito.verify(mContextMock).getString(EXPECTED_VALUE_THAT_SHOULD_BE_PASSED);

Verify no more interaction of a mock instance

Mockito.verifyNoMoreInteractions(someMockInstance);

Verify if a List has some items and check their size

assertThat(list, (hasItems("android", "context")));
assertThat(list, allOf(hasSize(greaterThan(3)), hasSize(lessThan(12))));

Verify the type of class posted in argument captor

assertThat(ac.getValue(), is(CoreMatchers.instanceOf(SomeClassName.class)));

Assert if a specific exception was thrown

@Test(expected = NullPointerException.class)
public void dummy() {
/*
* Test will not pass if 
* NullPointerExceptio is not thrown
* */
throw new NullPointerException();
}

Manually invoke callbacks with mockito

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Callback callback = (Callback) invocation.getArguments()[1];
        callback.onGetContactsSucceeded(getDummyContactSchemaList());
        return null;
    }
}).when(mHttpEndpoint).getContacts(anyString(), any(Callback.class));

Test Class Template

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

#parse("File Header.java")
@RunWith(MockitoJUnitRunner.class)
public class ${NAME} {
  ${BODY}
  @Before
  public void setup() throws Exception {
    
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment