Mockito
- Don’t mock too much, only mock directly dependence
- Steps: create mock:@Mock -> stubbing:when/thenReturn -> Verify: verify
- @Spy: used to wrap a real object. Every call, unless specified otherwise, is delegated to the object.
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
// When can't use @RunWith, for example test class already extends another base class.
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
// Annotations
@Mock
Mockito.mock(XX.class) // or
@Spy
@InjectMocks
@Captor
ArgumentCaptor<XClass> captor=ArgumentCaptor.forClass(XClass.class);
verify(mock).doSomething(capto.capture());
// Stubbing
when(mockObj.someMethod(0)).thenReturn("someThing");
when(mockObj.someMethod(1)).thenThrow(new RuntimeException());
when(instance.someMethod()).thenReturn(someValue);
thenThrow(Throwable)
thenCallRealMethod()
doReturn|Answer|Throw()
- Important gotcha on spying real objects!
- use doReturn|Answer|Throw() to stub spy object
- use doXXX on void methods
// spy instance field
Typex ox = Mockito.spy(anObject.aField);
anObject.aField = ox;
doReturn("some").when(spyObj).someMethod();
doCallRealMethod().when(instance).voidMethod();
doThrow(new Exception()).when(instance).voidMethod()
verify(mockObj, never()).someMethod(param);
verifyZeroInteractions(mock...);
verify(mockObj, atLeast(2)).someMethod();
verify(mockObj, times(3)).someMethod();
reset
- after reset
Mock chained calls
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
SomeService service;
when(service.getX().getY()).thenReturn(Z);
Do different things when call multiple times
Invalid use of argument matchers!
- When using matchers, all arguments have to be provided by matchers.
//incorrect:
someMethod(anyObject(), "raw String");
// Should be
someMethod(anyObject(), eq("raw String"));
UnfinishedVerificationException: Missing method call for verify(mock)
- in verify, use any() for primitive arguments
Testing Servlet
when(request.getParameter("user")).thenReturn("userA");
verify(response).setContentType("plain/text");
verify(response).addHeader("headerA")).thenReturn("value");
Hamcrest
- More Readable.
- Provides Better Failure Messages
- Type Safety
- hasItem, contains, containsInAnyOrder
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
org.hamcrest.Matchers
containsString, startsWith, endsWith, equalTo,equalToIgnoringCase, equalToIgnoringWhitespace, isEmpty, isEmptyOrNull and stringContainsInOrder
assertThat(actual, containsString(expected));
assertThat(actual, nullValue());
assertThat(actual, notNullValue());
assertThat(subClass, instanceOf(BaseClass.class));
[TestNG]
Spring + JUnit
Using REST Assured to test http APIs
Response rsp = given().filter(sessionFilter).when().get(someUrl).then().statusCode(is(200))).extract().response()
Map importResult = rsp.as(Map[].class)[0];
assertThat(Boolean.valueOf(importResult.get("success").toString()), is(true));
randomizedtesting
@RunWith(RandomizedRunner.class)
@Seed("the-seed")
@com.carrotsearch.randomizedtesting.annotations.Repeat(iterations = 5)
Eclipse
Plugins
- MoreUnit
- Ctrl+U: create test method
- Ctrl+J: jump to test method
Add Static Import Automatically
- To help write test cases easier, when we type “assertT” and hit Ctrl+Space, we want Eclipse to add static import automatically for us: import static org.hamcrest.MatcherAssert.assertThat;
- Go to Window > Preferences > Java > Editor > Content Assist > Favorites, then add:
org.hamcrest
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*
org.mockito.Mockito
org.mockito.Matchers
org.mockito.ArgumentMatchers
io.restassured.RestAssured
Run Tests across Multiple Projects
Create a maven project depending on all the projects you want to test.
Create Test code:
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;
@RunWith(ClasspathSuite.class)
public class TestRunner {
}
Maven
- Run specific method: mvn test -Dtest=className#methodName
Misc
- json-server - Get a full fake REST API Server
- Loading test
- JMeter
- Tsung
- locustio