BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,26 @@
package com.baeldung.mockito.callbacks;
public class ActionHandler {
private Service service;
public ActionHandler(Service service) {
this.service = service;
}
public void doAction() {
service.doAction("our-request", new Callback<Response>() {
@Override
public void reply(Response response) {
handleResponse(response);
}
});
}
private void handleResponse(Response response) {
if (response.isValid()) {
response.setData(new Data("Successful data response"));
}
}
}
@@ -0,0 +1,6 @@
package com.baeldung.mockito.callbacks;
public interface Callback<T> {
void reply(T response);
}
@@ -0,0 +1,15 @@
package com.baeldung.mockito.callbacks;
public class Data {
private String message;
public Data(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.mockito.callbacks;
public class Response {
private Data data;
private boolean isValid = true;
public boolean isValid() {
return isValid;
}
public void setIsValid(boolean isValid) {
this.isValid = isValid;
}
public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.mockito.callbacks;
public interface Service {
void doAction(String request, Callback<Response> callback);
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,10 @@
package com.baeldung.mockito;
public final class FinalList extends MyList {
@Override
public int size() {
return 1;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.mockito;
import org.junit.Test;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MockFinals {
@Test
public void whenMockFinalClassMockWorks() {
FinalList finalList = new FinalList();
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertNotEquals(mock.size(), finalList.size());
}
@Test
public void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertNotEquals(mock.finalMethod(), myList.finalMethod());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.mockito;
import org.junit.Test;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.baeldung.mockito.MyList;
public class MockFinalsUnitTest {
@Test
public void whenMockFinalClassMockWorks() {
FinalList finalList = new FinalList();
FinalList mock = mock(FinalList.class);
when(mock.size()).thenReturn(2);
assertNotEquals(mock.size(), finalList.size());
}
@Test
public void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();
MyList mock = mock(MyList.class);
when(mock.finalMethod()).thenReturn(1);
assertNotEquals(mock.finalMethod(), myList.finalMethod());
}
}
@@ -0,0 +1,114 @@
package com.baeldung.mockito;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
//@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationIntegrationTest {
@Mock
private List<String> mockedList;
@Spy
private List<String> spiedList = new ArrayList<>();
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
// tests
@Test
public void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
mockList.add("one");
Mockito.verify(mockList).add("one");
assertEquals(0, mockList.size());
Mockito.when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
@Test
public void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
Mockito.when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Test
public void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = Mockito.spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
assertEquals(2, spyList.size());
Mockito.doReturn(100).when(spyList).size();
assertEquals(100, spyList.size());
}
@Test
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
Mockito.verify(spiedList).add("one");
Mockito.verify(spiedList).add("two");
assertEquals(2, spiedList.size());
Mockito.doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
@Test
public void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
Mockito.verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
@Captor
private
ArgumentCaptor<String> argCaptor;
@Test
public void whenUseCaptorAnnotation_thenTheSam() {
mockedList.add("one");
Mockito.verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
@Test
public void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord"));
}
}
@@ -0,0 +1,114 @@
package com.baeldung.mockito;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
//@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationUnitTest {
@Mock
private List<String> mockedList;
@Spy
private List<String> spiedList = new ArrayList<>();
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
// tests
@Test
public void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
mockList.add("one");
Mockito.verify(mockList).add("one");
assertEquals(0, mockList.size());
Mockito.when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
@Test
public void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
Mockito.when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Test
public void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = Mockito.spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
assertEquals(2, spyList.size());
Mockito.doReturn(100).when(spyList).size();
assertEquals(100, spyList.size());
}
@Test
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
Mockito.verify(spiedList).add("one");
Mockito.verify(spiedList).add("two");
assertEquals(2, spiedList.size());
Mockito.doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
@Test
public void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
Mockito.verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
@Captor
private
ArgumentCaptor<String> argCaptor;
@Test
public void whenUseCaptorAnnotation_thenTheSam() {
mockedList.add("one");
Mockito.verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
@Test
public void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord"));
}
}
@@ -0,0 +1,95 @@
package com.baeldung.mockito;
import org.junit.Test;
import org.mockito.Mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class MockitoConfigExamplesIntegrationTest {
// tests
@Test
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));
}
@Test
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));
}
@Test(expected = IllegalStateException.class)
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test(expected = NullPointerException.class)
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = Mockito.mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
listMock.clear();
}
@Test
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test(expected = IllegalStateException.class)
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
}
@Test
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();
assertThat(listMock.size(), equalTo(1));
}
@Test
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));
}
@Test(expected = NullPointerException.class)
public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
final MyList instance = new MyList();
final MyList spy = Mockito.spy(instance);
doThrow(NullPointerException.class).when(spy).size();
spy.size();
}
}
@@ -0,0 +1,97 @@
package com.baeldung.mockito;
import org.junit.Test;
import org.mockito.Mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import com.baeldung.mockito.MyList;
public class MockitoConfigExamplesUnitTest {
// tests
@Test
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));
}
@Test
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added, is(false));
}
@Test(expected = IllegalStateException.class)
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test(expected = NullPointerException.class)
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = Mockito.mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
listMock.clear();
}
@Test
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test(expected = IllegalStateException.class)
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
}
@Test
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();
assertThat(listMock.size(), equalTo(1));
}
@Test
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));
}
@Test(expected = NullPointerException.class)
public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
final MyList instance = new MyList();
final MyList spy = Mockito.spy(instance);
doThrow(NullPointerException.class).when(spy).size();
spy.size();
}
}
@@ -0,0 +1,55 @@
package com.baeldung.mockito;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
public class MockitoExceptionIntegrationTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
}
}
@@ -0,0 +1,57 @@
package com.baeldung.mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
public class MockitoExceptionUnitTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
}
}
@@ -0,0 +1,37 @@
package com.baeldung.mockito;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Map;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class MockitoInjectIntoSpyUnitTest {
@Before
public void init() {
MockitoAnnotations.initMocks(this);
spyDic = Mockito.spy(new MyDictionary(wordMap));
}
@Mock
private Map<String, String> wordMap;
@InjectMocks
private MyDictionary dic = new MyDictionary();
private MyDictionary spyDic;
@Test
public void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
}
}
@@ -0,0 +1,69 @@
package com.baeldung.mockito;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooLittleActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
public class MockitoMockIntegrationTest {
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
thrown.expect(TooLittleActualInvocations.class);
thrown.expectMessage(containsString("myMock.add"));
verify(listMock, times(2)).add(anyString());
}
@Test
public void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithSettings_thenCorrect() {
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
MyList listMock = mock(MyList.class, customSettings);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
}
@@ -0,0 +1,72 @@
package com.baeldung.mockito;
import static org.mockito.Mockito.*;
import com.baeldung.mockito.MyList;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.containsString;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooLittleActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MockitoMockUnitTest {
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
thrown.expect(TooLittleActualInvocations.class);
thrown.expectMessage(containsString("myMock.add"));
verify(listMock, times(2)).add(anyString());
}
@Test
public void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithSettings_thenCorrect() {
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
MyList listMock = mock(MyList.class, customSettings);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
}
@@ -0,0 +1,117 @@
package com.baeldung.mockito;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import java.util.List;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class MockitoVerifyExamplesIntegrationTest {
// tests
@Test
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList).size();
}
@Test
public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, times(1)).size();
}
@Test
public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyZeroInteractions(mockedList);
}
@Test
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();
}
@Test(expected = NoInteractionsWanted.class)
public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();
verify(mockedList).size();
verifyNoMoreInteractions(mockedList);
}
@Test
public final void whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
mockedList.clear();
final InOrder inOrder = Mockito.inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();
}
@Test
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, never()).clear();
}
@Test
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.clear();
mockedList.clear();
mockedList.clear();
verify(mockedList, atLeast(1)).clear();
verify(mockedList, atMost(10)).clear();
}
// with arguments
@Test
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add("test");
}
@Test
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add(anyString());
}
@Test
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement"));
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
assertThat(capturedArgument, hasItem("someElement"));
}
}
@@ -0,0 +1,119 @@
package com.baeldung.mockito;
import com.google.common.collect.Lists;
import com.baeldung.mockito.MyList;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import java.util.List;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class MockitoVerifyExamplesUnitTest {
// tests
@Test
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList).size();
}
@Test
public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, times(1)).size();
}
@Test
public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyZeroInteractions(mockedList);
}
@Test
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verify(mockedList, times(0)).size();
}
@Test(expected = NoInteractionsWanted.class)
public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();
verify(mockedList).size();
verifyNoMoreInteractions(mockedList);
}
@Test
public final void whenVerifyingOrderOfInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.add("a parameter");
mockedList.clear();
final InOrder inOrder = Mockito.inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();
}
@Test
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
verify(mockedList, never()).clear();
}
@Test
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.clear();
mockedList.clear();
mockedList.clear();
verify(mockedList, atLeast(1)).clear();
verify(mockedList, atMost(10)).clear();
}
// with arguments
@Test
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add("test");
}
@Test
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
verify(mockedList).add(anyString());
}
@Test
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement"));
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
assertThat(capturedArgument, hasItem("someElement"));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.mockito;
import java.util.HashMap;
import java.util.Map;
class MyDictionary {
private Map<String, String> wordMap;
MyDictionary() {
wordMap = new HashMap<>();
}
MyDictionary(Map<String, String> wordMap) {
this.wordMap = wordMap;
}
public void add(final String word, final String meaning) {
wordMap.put(word, meaning);
}
String getMeaning(final String word) {
return wordMap.get(word);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.mockito;
import java.util.AbstractList;
public class MyList extends AbstractList<String> {
@Override
public String get(final int index) {
return null;
}
@Override
public int size() {
return 1;
}
@Override
public void add(int index, String element) {
// no-op
}
final public int finalMethod() {
return 0;
}
}
@@ -0,0 +1,65 @@
package com.baeldung.mockito.callbacks;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
public class ActionHandlerUnitTest {
@Mock
private Service service;
@Captor
private ArgumentCaptor<Callback<Response>> callbackCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void givenServiceWithValidResponse_whenCallbackReceived_thenProcessed() {
ActionHandler handler = new ActionHandler(service);
handler.doAction();
verify(service).doAction(anyString(), callbackCaptor.capture());
Callback<Response> callback = callbackCaptor.getValue();
Response response = new Response();
callback.reply(response);
String expectedMessage = "Successful data response";
Data data = response.getData();
assertEquals("Should receive a successful message: ", expectedMessage, data.getMessage());
}
@Test
public void givenServiceWithInvalidResponse_whenCallbackReceived_thenNotProcessed() {
Response response = new Response();
response.setIsValid(false);
doAnswer((Answer<Void>) invocation -> {
Callback<Response> callback = invocation.getArgument(1);
callback.reply(response);
Data data = response.getData();
assertNull("No data in invalid response: ", data);
return null;
}).when(service)
.doAction(anyString(), any(Callback.class));
ActionHandler handler = new ActionHandler(service);
handler.doAction();
}
}
@@ -0,0 +1,63 @@
package com.baeldung.mockito.voidmethods;
import com.baeldung.mockito.MyList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MockitoVoidMethodsUnitTest {
@Test
public void whenAddCalledVerified() {
MyList mockVoid = mock(MyList.class);
mockVoid.add(0, "");
verify(mockVoid, times(1)).add(0, "");
}
@Test(expected = Exception.class)
public void givenNull_addThrows() {
MyList mockVoid = mock(MyList.class);
doThrow().when(mockVoid).add(isA(Integer.class), isNull());
mockVoid.add(0, null);
}
@Test
public void whenAddCalledValueCaptured() {
MyList mockVoid = mock(MyList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture());
mockVoid.add(0, "captured");
assertEquals("captured", valueCapture.getValue());
}
@Test
public void whenAddCalledAnswered() {
MyList mockVoid = mock(MyList.class);
doAnswer((Answer<Void>) invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
//do something with the arguments here
assertEquals(3, arg0);
assertEquals("answer me", arg1);
return null;
}).when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(3, "answer me");
}
@Test
public void whenAddCalledRealMethodCalled() {
MyList mockVoid = mock(MyList.class);
doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class));
mockVoid.add(1, "real");
verify(mockVoid, times(1)).add(1, "real");
}
}
@@ -0,0 +1,20 @@
package com.baeldung.powermockito.introduction;
class CollaboratorForPartialMocking {
static String staticMethod() {
return "Hello Baeldung!";
}
final String finalMethod() {
return "Hello Baeldung!";
}
private String privateMethod() {
return "Hello Baeldung!";
}
String privateMethodCaller() {
return privateMethod() + " Welcome to the Java world.";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.powermockito.introduction;
class CollaboratorWithFinalMethods {
final String helloMethod() {
return "Hello World!";
}
}
@@ -0,0 +1,16 @@
package com.baeldung.powermockito.introduction;
class CollaboratorWithStaticMethods {
static String firstMethod(String name) {
return "Hello " + name + " !";
}
static String secondMethod() {
return "Hello no one!";
}
static String thirdMethod() {
return "Hello no one again!";
}
}
@@ -0,0 +1,28 @@
package com.baeldung.powermockito.introduction;
class LuckyNumberGenerator {
public int getLuckyNumber(String name) {
saveIntoDatabase(name);
if (name == null) {
return getDefaultLuckyNumber();
}
return getComputedLuckyNumber(name.length());
}
private void saveIntoDatabase(String name) {
// Save the name into the database
}
private int getDefaultLuckyNumber() {
return 100;
}
private int getComputedLuckyNumber(int length) {
return length < 5 ? 5 : 10000;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.powermockito.introduction;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator")
public class LuckyNumberGeneratorUnitTest {
@Test
public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
when(mock, "getDefaultLuckyNumber").thenReturn(300);
int result = mock.getLuckyNumber(null);
assertEquals(300, result);
}
@Test
public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt());
int result = mock.getLuckyNumber("Jack");
assertEquals(1, result);
}
@Test
public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
int result = mock.getLuckyNumber("Tyranosorous");
verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString());
assertEquals(10000, result);
}
}
@@ -0,0 +1,79 @@
package com.baeldung.powermockito.introduction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")
public class PowerMockitoUnitTest {
@Test
public void givenFinalMethods_whenUsingPowerMockito_thenCorrect() throws Exception {
CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);
whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);
CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();
when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");
String welcome = collaborator.helloMethod();
verify(collaborator).helloMethod();
assertEquals("Hello Baeldung!", welcome);
}
@Test(expected = RuntimeException.class)
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
mockStatic(CollaboratorWithStaticMethods.class);
when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString())).thenReturn("Hello Baeldung!");
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");
doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
CollaboratorWithStaticMethods.thirdMethod();
String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");
assertEquals("Hello Baeldung!", firstWelcome);
assertEquals("Hello Baeldung!", secondWelcome);
verifyStatic(CollaboratorWithStaticMethods.class, times(2));
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
verifyStatic(CollaboratorWithStaticMethods.class, Mockito.never());
CollaboratorWithStaticMethods.secondMethod();
CollaboratorWithStaticMethods.thirdMethod();
}
@Test
public void givenPartialMocking_whenUsingPowerMockito_thenCorrect() throws Exception {
String returnValue;
spy(CollaboratorForPartialMocking.class);
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");
returnValue = CollaboratorForPartialMocking.staticMethod();
CollaboratorForPartialMocking.staticMethod();
assertEquals("I am a static mock method.", returnValue);
CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
CollaboratorForPartialMocking mock = spy(collaborator);
when(mock.finalMethod()).thenReturn("I am a final mock method.");
returnValue = mock.finalMethod();
verify(mock,times(3)).finalMethod();
assertEquals("I am a final mock method.", returnValue);
when(mock, "privateMethod").thenReturn("I am a private mock method.");
returnValue = mock.privateMethodCaller();
verifyPrivate(mock).invoke("privateMethod");
assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);
}
}