Java 13914 (#13083)

* [JAVA-13914] Replaced Junit4 annotations with Junit5

* [JAVA-13914] Replaced Junit4 annotations with Junit5

* [JAVA-13914] Fixed test

* [JAVA-13914] Clean up

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos 2022-12-08 14:17:51 +00:00 committed by GitHub
parent 205506f00a
commit 0264bb82c8
17 changed files with 307 additions and 242 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.app.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
@ -10,18 +11,18 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.app.api.Flower;
import com.baeldung.domain.service.FlowerService;
@RunWith(MockitoJUnitRunner.class)
public class FlowerControllerUnitTest {
@ExtendWith(MockitoExtension.class)
class FlowerControllerUnitTest {
@InjectMocks
private FlowerController flowerController;
@ -30,7 +31,7 @@ public class FlowerControllerUnitTest {
private FlowerService flowerService;
@Test
public void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
doReturn("Flower").when(flowerService).analyze("poppy");
String response = flowerController.isAFlower("poppy");
@ -38,25 +39,27 @@ public class FlowerControllerUnitTest {
}
@Test
public void givenAnyString_whenUsingArgumentMatcher_thenCorrect() {
void givenAnyString_whenUsingArgumentMatcher_thenCorrect() {
when(flowerService.analyze(anyString())).thenReturn("Flower");
String response = flowerController.isAFlower("violetta");
assertThat(response).isEqualTo("Flower");
}
@Test(expected = InvalidUseOfMatchersException.class)
public void whenIncorrectMatchers_thenThrowsError() {
when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true);
@Test
void whenIncorrectMatchers_thenThrowsError() {
assertThrows(InvalidUseOfMatchersException.class, () -> {
when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true);
});
Flower flower = new Flower("poppy", 15);
Boolean response = flowerController.isABigFlower(flower);
assertThat(response).isTrue();
assertThat(response).isFalse();
}
@Test
public void whenCorrectMatchers_thenCorrect() {
void whenCorrectMatchers_thenCorrect() {
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
Flower flower = new Flower("poppy", 15);
@ -65,23 +68,25 @@ public class FlowerControllerUnitTest {
assertThat(response).isTrue();
}
@Test(expected = InvalidUseOfMatchersException.class)
public void whenUsingMatchersAsReturnValue_thenThrowsError() {
@Test
void whenUsingMatchersAsReturnValue_thenThrowsError() {
flowerController.isAFlower("poppy");
String orMatcher = or(eq("poppy"), endsWith("y"));
verify(flowerService).analyze(orMatcher);
assertThrows(InvalidUseOfMatchersException.class, () -> {
verify(flowerService).analyze(orMatcher);
});
}
@Test
public void whenUsingMatchersAsOngoingStubbing_thenCorrect1() {
void whenUsingMatchersAsOngoingStubbing_thenCorrect1() {
flowerController.isAFlower("poppy");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
}
@Test
public void whenUsingMatchersAsOngoingStubbing_thenCorrect2() {
void whenUsingMatchersAsOngoingStubbing_thenCorrect2() {
flowerController.isAFlower("lily");
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));

View File

@ -5,52 +5,52 @@ import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.app.api.MessageDTO;
import com.baeldung.domain.model.Message;
import com.baeldung.domain.service.MessageService;
import com.baeldung.domain.util.MessageMatcher;
@RunWith(MockitoJUnitRunner.class)
public class MessageControllerUnitTest {
@ExtendWith(MockitoExtension.class)
class MessageControllerUnitTest {
@InjectMocks
private MessageController messageController;
@Mock
private MessageService messageService;
@InjectMocks
private MessageController messageController;
@Test
public void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
@Mock
private MessageService messageService;
messageController.createMessage(messageDTO);
@Test
void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(any(Message.class));
}
messageController.createMessage(messageDTO);
@Test
public void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(any(Message.class));
}
messageController.createMessage(messageDTO);
@Test
void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
MessageDTO messageDTO = new MessageDTO();
messageDTO.setFrom("me");
messageDTO.setTo("you");
messageDTO.setText("Hello, you!");
Message message = new Message();
message.setFrom("me");
message.setTo("you");
message.setText("Hello, you!");
messageController.createMessage(messageDTO);
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
}
Message message = new Message();
message.setFrom("me");
message.setTo("you");
message.setText("Hello, you!");
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
}
}

View File

@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -13,7 +14,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
@ -115,7 +115,7 @@ class UserServiceUnitTest {
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
// Given
user = new User("jerry", 12);
Mockito.reset(userRepository);
reset(userRepository);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
// When

View File

@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class MockFinalsUnitTest {
class MockFinalsUnitTest {
@Test
public void whenMockFinalMethodMockWorks() {
void whenMockFinalMethodMockWorks() {
MyList myList = new MyList();

View File

@ -1,23 +1,27 @@
package com.baeldung.mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationUnitTest {
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationUnitTest {
@Mock
private List<String> mockedList;
@ -36,61 +40,61 @@ public class MockitoAnnotationUnitTest {
// tests
@Test
public void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
void whenNotUseMockAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
mockList.add("one");
Mockito.verify(mockList).add("one");
verify(mockList).add("one");
assertEquals(0, mockList.size());
Mockito.when(mockList.size()).thenReturn(100);
when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
@Test
public void whenUseMockAnnotation_thenMockIsInjected() {
void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
Mockito.verify(mockedList).add("one");
verify(mockedList).add("one");
assertEquals(0, mockedList.size());
Mockito.when(mockedList.size()).thenReturn(100);
when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Test
public void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = Mockito.spy(new ArrayList<String>());
void whenNotUseSpyAnnotation_thenCorrect() {
final List<String> spyList = spy(new ArrayList<String>());
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
verify(spyList).add("one");
verify(spyList).add("two");
assertEquals(2, spyList.size());
Mockito.doReturn(100).when(spyList).size();
doReturn(100).when(spyList).size();
assertEquals(100, spyList.size());
}
@Test
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
Mockito.verify(spiedList).add("one");
Mockito.verify(spiedList).add("two");
verify(spiedList).add("one");
verify(spiedList).add("two");
assertEquals(2, spiedList.size());
Mockito.doReturn(100).when(spiedList).size();
doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
@Test
public void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = Mockito.mock(List.class);
void whenNotUseCaptorAnnotation_thenCorrect() {
final List<String> mockList = mock(List.class);
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
Mockito.verify(mockList).add(arg.capture());
verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
@ -100,9 +104,9 @@ public class MockitoAnnotationUnitTest {
ArgumentCaptor<String> argCaptor;
@Test
public void whenUseCaptorAnnotation_thenTheSame() {
void whenUseCaptorAnnotation_thenTheSame() {
mockedList.add("one");
Mockito.verify(mockedList).add(argCaptor.capture());
verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@ -114,8 +118,8 @@ public class MockitoAnnotationUnitTest {
private MyDictionary dic = new MyDictionary();
@Test
public void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", dic.getMeaning("aWord"));
}

View File

@ -6,16 +6,18 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
@Rule
public MockitoRule initRule = MockitoJUnit.rule();
@Mock
private List<String> mockedList;
@ -23,6 +25,6 @@ public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
when(mockedList.size()).thenReturn(41);
assertThat(mockedList.size()).isEqualTo(41);
assertThat(mockedList).hasSize(41);
}
}

View File

@ -1,22 +1,28 @@
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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Map;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationsInjectIntoSpyUnitTest {
@ExtendWith(MockitoExtension.class)
class MockitoAnnotationsInjectIntoSpyUnitTest {
@Before
@BeforeEach
public void init() {
MockitoAnnotations.openMocks(this);
spyDic = Mockito.spy(new MyDictionary(wordMap));
openMocks(this);
spyDic = spy(new MyDictionary(wordMap));
}
@Mock
@ -28,8 +34,8 @@ public class MockitoAnnotationsInjectIntoSpyUnitTest {
private MyDictionary spyDic;
@Test
public void whenUseInjectMocksAnnotation_thenCorrect() {
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
void whenUseInjectMocksAnnotation_thenCorrect() {
when(wordMap.get("aWord")).thenReturn("aMeaning");
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
}

View File

@ -1,18 +1,23 @@
package com.baeldung.mockito;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.util.List;
public class MockitoAnnotationsUninitializedUnitTest {
class MockitoAnnotationsUninitializedUnitTest {
@Mock
List<String> mockedList;
@Test(expected = NullPointerException.class)
public void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
Mockito.when(mockedList.size()).thenReturn(1);
@Test
void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
assertThrows(NullPointerException.class, () -> {
when(mockedList.size()).thenReturn(1);
});
}
}

View File

@ -1,57 +1,71 @@
package com.baeldung.mockito;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
public class MockitoExceptionUnitTest {
@ExtendWith(MockitoExtension.class)
class MockitoExceptionUnitTest {
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
@Test
void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
@Test
void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(IllegalStateException.class).when(dictMock)
.add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> {
dictMock.add("word", "meaning");
});
dictMock.add("word", "meaning");
}
@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
@Test
void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
assertThrows(NullPointerException.class, () -> {
dictMock.getMeaning("word");
});
dictMock.getMeaning("word");
}
@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
@Test
void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
MyDictionary dictMock = mock(MyDictionary.class);
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
.add(anyString(), anyString());
assertThrows(IllegalStateException.class, () -> {
dictMock.add("word", "meaning");
});
dictMock.add("word", "meaning");
}
// =====
@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
@Test
void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
MyDictionary dict = new MyDictionary();
MyDictionary spy = Mockito.spy(dict);
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
spy.getMeaning("word");
assertThrows(NullPointerException.class, () -> {
spy.getMeaning("word");
});
}
}

View File

@ -10,16 +10,16 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MockitoMockUnitTest {
class MockitoMockUnitTest {
@Test
public void whenUsingSimpleMock_thenCorrect() {
void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6));
@ -29,7 +29,7 @@ public class MockitoMockUnitTest {
}
@Test
public void whenUsingMockWithName_thenCorrect() {
void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
@ -47,7 +47,7 @@ public class MockitoMockUnitTest {
}
@Test
public void whenUsingMockWithAnswer_thenCorrect() {
void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
@ -56,7 +56,7 @@ public class MockitoMockUnitTest {
}
@Test
public void whenUsingMockWithSettings_thenCorrect() {
void whenUsingMockWithSettings_thenCorrect() {
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
MyList listMock = mock(MyList.class, customSettings);
boolean added = listMock.add(randomAlphabetic(6));

View File

@ -1,9 +1,11 @@
package com.baeldung.mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@ -13,69 +15,71 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import com.google.common.collect.Lists;
public class MockitoVerifyExamplesUnitTest {
class MockitoVerifyExamplesUnitTest {
// tests
@Test
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
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 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 void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
verifyNoInteractions(mockedList);
}
@Test
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
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() {
@Test
final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
mockedList.clear();
verify(mockedList).size();
verifyNoMoreInteractions(mockedList);
assertThrows(NoInteractionsWanted.class, () -> {
verifyNoMoreInteractions(mockedList);
});
}
@Test
public final void whenVerifyingOrderOfInteractions_thenCorrect() {
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);
final InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).size();
inOrder.verify(mockedList).add("a parameter");
inOrder.verify(mockedList).clear();
}
@Test
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.size();
@ -83,7 +87,7 @@ public class MockitoVerifyExamplesUnitTest {
}
@Test
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.clear();
mockedList.clear();
@ -96,7 +100,7 @@ public class MockitoVerifyExamplesUnitTest {
// with arguments
@Test
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
@ -104,7 +108,7 @@ public class MockitoVerifyExamplesUnitTest {
}
@Test
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.add("test");
@ -112,7 +116,7 @@ public class MockitoVerifyExamplesUnitTest {
}
@Test
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String>newArrayList("someElement"));

View File

@ -2,21 +2,24 @@ package com.baeldung.mockito;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
import org.junit.jupiter.api.Test;
public class MockitoWhenThenExamplesUnitTest {
class MockitoWhenThenExamplesUnitTest {
@Test
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
final boolean added = listMock.add(randomAlphabetic(6));
@ -24,67 +27,79 @@ public class MockitoWhenThenExamplesUnitTest {
}
@Test
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = Mockito.mock(MyList.class);
final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
final MyList listMock = mock(MyList.class);
doReturn(false).when(listMock).add(anyString());
final boolean added = listMock.add(randomAlphabetic(6));
assertThat(added).isFalse();
}
@Test(expected = IllegalStateException.class)
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
@Test
final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
});
}
@Test
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
}
@Test(expected = NullPointerException.class)
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = Mockito.mock(MyList.class);
@Test
final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
final MyList listMock = mock(MyList.class);
doThrow(NullPointerException.class).when(listMock).clear();
listMock.clear();
assertThrows(NullPointerException.class, () -> {
listMock.clear();
});
}
@Test(expected = IllegalStateException.class)
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = Mockito.mock(MyList.class);
@Test
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
final MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
assertThrows(IllegalStateException.class, () -> {
listMock.add(randomAlphabetic(6));
listMock.add(randomAlphabetic(6));
});
}
@Test(expected = NullPointerException.class)
public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
@Test
final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
final MyList instance = new MyList();
final MyList spy = Mockito.spy(instance);
final MyList spy = spy(instance);
doThrow(NullPointerException.class).when(spy).size();
spy.size();
assertThrows(NullPointerException.class, () -> {
spy.size();
});
}
@Test
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = mock(MyList.class);
when(listMock.size()).thenCallRealMethod();
assertThat(listMock).hasSize(1);
}
@Test
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);

View File

@ -3,18 +3,20 @@ package com.baeldung.mockito.argumentcaptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class)
public class EmailServiceUnitTest {
@ExtendWith(MockitoExtension.class)
class EmailServiceUnitTest {
@Mock
DeliveryPlatform platform;
@ -29,34 +31,34 @@ public class EmailServiceUnitTest {
ArgumentCaptor<Credentials> credentialsCaptor;
@Test
public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor";
String body = "Hey, let'use ArgumentCaptor";
emailService.send(to, subject, body, false);
Mockito.verify(platform).deliver(emailCaptor.capture());
verify(platform).deliver(emailCaptor.capture());
Email emailCaptorValue = emailCaptor.getValue();
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
}
@Test
public void whenDoesSupportHtml_expectHTMLEmailFormat() {
void whenDoesSupportHtml_expectHTMLEmailFormat() {
String to = "info@baeldung.com";
String subject = "Using ArgumentCaptor";
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
emailService.send(to, subject, body, true);
Mockito.verify(platform).deliver(emailCaptor.capture());
verify(platform).deliver(emailCaptor.capture());
Email value = emailCaptor.getValue();
assertThat(value.getFormat()).isEqualTo(Format.HTML);
}
@Test
public void whenServiceRunning_expectUpResponse() {
Mockito.when(platform.getServiceStatus()).thenReturn("OK");
void whenServiceRunning_expectUpResponse() {
when(platform.getServiceStatus()).thenReturn("OK");
ServiceStatus serviceStatus = emailService.checkServiceStatus();
@ -64,8 +66,8 @@ public class EmailServiceUnitTest {
}
@Test
public void whenServiceNotRunning_expectDownResponse() {
Mockito.when(platform.getServiceStatus()).thenReturn("Error");
void whenServiceNotRunning_expectDownResponse() {
when(platform.getServiceStatus()).thenReturn("Error");
ServiceStatus serviceStatus = emailService.checkServiceStatus();
@ -73,26 +75,26 @@ public class EmailServiceUnitTest {
}
@Test
public void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials));
}
@Test
public void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
assertTrue(emailService.authenticatedSuccessfully(credentials));
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
}
@Test
public void whenNotAuthenticated_expectFalse() {
void whenNotAuthenticated_expectFalse() {
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
assertFalse(emailService.authenticatedSuccessfully(credentials));
}

View File

@ -2,9 +2,9 @@ package com.baeldung.mockito.mockedstatic;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mockStatic;
import java.util.Arrays;
@ -14,7 +14,7 @@ class MockedStaticUnitTest {
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
utilities.when(StaticUtils::name).thenReturn("Eugen");
assertThat(StaticUtils.name()).isEqualTo("Eugen");
}
@ -26,7 +26,7 @@ class MockedStaticUnitTest {
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
utilities.when(() -> StaticUtils.range(2, 6))
.thenReturn(Arrays.asList(10, 11, 12));

View File

@ -2,29 +2,30 @@ package com.baeldung.mockito.spy;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.mockito.Mockito;
import org.junit.jupiter.api.Test;
import org.mockito.exceptions.misusing.NotAMockException;
public class MockitoMisusingMockOrSpyUnitTest {
class MockitoMisusingMockOrSpyUnitTest {
@Test
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
List<String> list = new ArrayList<String>();
assertThatThrownBy(() -> Mockito.doReturn(100).when(list).size())
assertThatThrownBy(() -> doReturn(100).when(list).size())
.isInstanceOf(NotAMockException.class)
.hasMessageContaining("Argument passed to when() is not a mock!");
}
@Test
public void givenASpy_whenDoReturn_thenNoError() {
final List<String> spyList = Mockito.spy(new ArrayList<>());
void givenASpy_whenDoReturn_thenNoError() {
final List<String> spyList = spy(new ArrayList<>());
assertThatNoException().isThrownBy(() -> Mockito.doReturn(100).when(spyList).size());
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
}
}

View File

@ -1,30 +1,33 @@
package com.baeldung.mockito.spy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class MockitoSpyUnitTest {
@Test
public void whenSpyingOnList_thenCorrect() {
void whenSpyingOnList_thenCorrect() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = Mockito.spy(list);
final List<String> spyList = spy(list);
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
verify(spyList).add("one");
verify(spyList).add("two");
assertThat(spyList).hasSize(2);
}
@ -33,43 +36,43 @@ public class MockitoSpyUnitTest {
private List<String> aSpyList = new ArrayList<String>();
@Test
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
aSpyList.add("one");
aSpyList.add("two");
Mockito.verify(aSpyList).add("one");
Mockito.verify(aSpyList).add("two");
verify(aSpyList).add("one");
verify(aSpyList).add("two");
assertThat(aSpyList).hasSize(2);
}
@Test
public void whenStubASpy_thenStubbed() {
void whenStubASpy_thenStubbed() {
final List<String> list = new ArrayList<String>();
final List<String> spyList = Mockito.spy(list);
final List<String> spyList = spy(list);
assertEquals(0, spyList.size());
Mockito.doReturn(100).when(spyList).size();
doReturn(100).when(spyList).size();
assertThat(spyList).hasSize(100);
}
@Test
public void whenCreateMock_thenCreated() {
final List<String> mockedList = Mockito.mock(ArrayList.class);
void whenCreateMock_thenCreated() {
final List<String> mockedList = mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
verify(mockedList).add("one");
assertThat(mockedList).hasSize(0);
}
@Test
public void whenCreateSpy_thenCreate() {
final List<String> spyList = Mockito.spy(new ArrayList<>());
void whenCreateSpy_thenCreate() {
final List<String> spyList = spy(new ArrayList<>());
spyList.add("one");
Mockito.verify(spyList).add("one");
verify(spyList).add("one");
assertThat(spyList).hasSize(1);
}

View File

@ -1,6 +1,8 @@
package com.baeldung.mockito.voidmethods;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isNull;
@ -12,34 +14,36 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import com.baeldung.mockito.MyList;
@RunWith(MockitoJUnitRunner.class)
public class MockitoVoidMethodsUnitTest {
@ExtendWith(MockitoExtension.class)
class MockitoVoidMethodsUnitTest {
@Test
public void whenAddCalledVerified() {
void whenAddCalledVerified() {
MyList myList = mock(MyList.class);
myList.add(0, "");
verify(myList, times(1)).add(0, "");
}
@Test(expected = Exception.class)
public void givenNull_addThrows() {
@Test
void givenNull_addThrows() {
MyList myList = mock(MyList.class);
doThrow().when(myList).add(isA(Integer.class), isNull());
assertThrows(Exception.class, () -> {
doThrow().when(myList).add(isA(Integer.class), isNull());
});
myList.add(0, null);
}
@Test
public void whenAddCalledValueCaptured() {
void whenAddCalledValueCaptured() {
MyList myList = mock(MyList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
@ -49,7 +53,7 @@ public class MockitoVoidMethodsUnitTest {
}
@Test
public void whenAddCalledAnswered() {
void whenAddCalledAnswered() {
MyList myList = mock(MyList.class);
doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0);
@ -64,7 +68,7 @@ public class MockitoVoidMethodsUnitTest {
}
@Test
public void whenAddCalledRealMethodCalled() {
void whenAddCalledRealMethodCalled() {
MyList myList = mock(MyList.class);
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
myList.add(1, "real");