Java – JUnit + Mockito + Powermock + Spting Unit-Test

This Page studies JUnit (not TestNG) + Mockito (not EasyMock) + Powermock + Spting Unit-Test

  • JUnit – 4.12
  • Mockito – 1.10.19
  • Powermock – 1.6.3
  • Spring MockMvc – 4.3.15

JUnit test executors available, one for JUnit 4.4-4.12, one for JUnit 4.0-4.3. The test executor for JUnit 3 is not avaliable since PowerMock 2.0.

Reference:

AssertJ

## Unit Test
### Links
* [My Mokito Note](https://docs.google.com/document/d/1MPxKkj8sAeGuSJGubc8MuX37Wjuq0I1QD4cA7URD32c/edit#heading=h.3a1h6dlhu2xf)
* [MockMvc Manual](http://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html)
* [Testing async responses using MockMvc](https://sdqali.in/blog/2015/11/24/testing-async-responses-using-mockmvc/)
* [12. Spring MVC Test Integration](https://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html)
* [Mockito Baeldung Tutorial](http://www.baeldung.com/category/mockito/)

### Documents
- [Reflection](reflection.md)
- [gdoc unit test](https://docs.google.com/open?id=1lfkmvSwB0nDj_R-72N8XYW_X7t1CWINXY-UMxjHHEQo)

##### HOWTos PowerMockito
- Mock constructor
- Mock Private
- Mock static
- Mock static private

##### Mock Object
- Mock
- spy

##### Mock method
- when
- do

##### Validate
- validate
- Captor


#### Real Example

##### Annotations in Class.
-   @VisibleForTesting
-   @TestOnly


##### init Mock
@RunWith(MockitoJUnitRunner.class)
or
MockitoAnnotations.initMocks(this);


##### PowerMockito public class NinaJSONConversionServiceImplTest {
```
@RunWith(PowerMockRunner.class)
@PrepareForTest(NinaCoachHelperAgentRegistry.class)


Mockito.when(ninaCoachSettingsManager.getSettingByAutomatonId(Mockito.anyObject())).thenReturn(ninaCoachSetting);
Mockito.when(ninaCoachSettingsManager.getNinaCoachEnabledAgentGroupIds()).thenReturn(Collections.EMPTY_SET);


ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
Mockito.verify(internalMessageServer, Mockito.times(1)).sendMessageToOne(captor.capture(), Mockito.any());
Assert.assertArrayEquals(MessageFields.TYPE_NINA_COACH_CONFERENCE_REQUEST, captor.getValue().getMessageType());

// PowerMock static
        mockStatic(NinaCoachHelperAgentRegistry.class);
        PowerMockito.when(NinaCoachHelperAgentRegistry.isTimedOut(anyLong(),anyLong(),anyLong(),anyLong())).thenReturn(false);
        
        // Using Captor
                ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
        Mockito.verify(internalMessageServer, Mockito.times(1)).sendMessageToOne(captor.capture(), Mockito.any());
        Assert.assertEquals("true", new String(captor.getValue().getProperty(MessageFields.KEY_NINA_COACH_ALLOW_TRANSFER)));

```



### assertThat
* [JUnit](https://examples.javacodegeeks.com/core-java/junit/junit-assertthat-example/)

```
2.1 Core Matchers
Before you start implementing your own Matcher’s, you should look at the core matchers that come with JUnit already. Here is a list of the matcher methods:

Core
any() Matches any object passed to it.
is() A matcher that checks if the given objects are equal.
describedAs() adds a description to the matcher
Logical
allOf() Takes an array of matchers and must all match the expected object.
anyOf() Takes an array of matcher and must match at least one of the matchers must report that it matches the target object.
not() Check if the object negates what was passed.
Object
equalTo() Equality check.
instanceOf() Check if an object is an instance of a given/expected object.
notNullValue() Check if the passed value is not null
nullValue() Tests whether the given object is null or not null.
sameInstance() Tests if the given object is the exact same instance as another.
```

```
package com.areyes1.junitassertrue.sample;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Before;
import org.junit.Test;

public class JUnitTestAssertThatAssertions {
 
 int totalNumberOfApplicants = 0;
 
 @Before
 public void setData(){
 this.totalNumberOfApplicants = 9;
 }
 
 @Test
 public void testAssertThatEqual() {
 assertThat("123",is("123"));
 }
 
 @Test
 public void testAssertThatNotEqual() {
 assertThat(totalNumberOfApplicants,is(123));
 }
 
 @Test
 public void testAssertThatObject() {
 assertThat("123",isA(String.class));
 }
 
 @Test
 public void testAssertThatWMessage(){
 assertThat("They are not equal!","123",is("1234"));
 }
}
```

```
3. Bonus: Custom Matchers for your assertThat
You can actually create our own matcher and simply using that on your junit test case. See example of the custom matcher below.

CustomMatcher.java

package com.areyes1.junitassertthat.sample;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

public class CustomMatcher {
 public static Matcher matches(final Object expected){
 return new BaseMatcher() {
 protected Object expectedObject = expected;
 public boolean matches(Object item) {
 return expectedObject.equals(item);
 }
 public void describeTo(Description description) {
 description.appendText(expectedObject.toString());
 }
 };
 }
}


package com.areyes1.junitassertthat.sample;

import static org.junit.Assert.*;
import static com.areyes1.junitassertthat.sample.CustomMatcher.*;
import static org.hamcrest.CoreMatchers.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

public class JUnitTestAssertThatCustomMatcher {

 ArrayList listOfValidStrings = new ArrayList();
 private String inputValue = new String("Hello");
 @Before
 public void setData(){
 listOfValidStrings.add("object_1");
 listOfValidStrings.add("object_2");
 listOfValidStrings.add("object_3");
 }
 
 @Test
 public void testLogic(){
 assertThat(inputValue,matches("Hello"));
 }
}
```


#### Reading a file 
- com.inq.api.plugins.integratedmessaging.gateways.cbaninaproxy.domain.TalkAgentRequestProxyWrapperTest#invalidSessionCacheTest
```
private static String readTextFile(String filePath) throws Exception {
    String requestStr = XmlJsonTestUtils.readResource(filePath);
    return requestStr;
}
```

Leave a Reply

Close Menu