JAVA-13721 Fixing the formatting
This commit is contained in:
parent
e5985b3739
commit
7b8fad5dc9
|
@ -29,14 +29,12 @@
|
||||||
<artifactId>spring-context</artifactId>
|
<artifactId>spring-context</artifactId>
|
||||||
<version>${spring-framework.version}</version>
|
<version>${spring-framework.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- utils -->
|
<!-- utils -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
|
|
|
@ -1,25 +1,25 @@
|
||||||
package com.baeldung.mockito.argumentcaptor;
|
package com.baeldung.mockito.argumentcaptor;
|
||||||
|
|
||||||
public class Credentials {
|
public class Credentials {
|
||||||
private final String name;
|
private final String name;
|
||||||
private final String password;
|
private final String password;
|
||||||
private final String key;
|
private final String key;
|
||||||
|
|
||||||
public Credentials(String name, String password, String key) {
|
public Credentials(String name, String password, String key) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.key = key;
|
this.key = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
return password;
|
return password;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.mockito.argumentcaptor;
|
package com.baeldung.mockito.argumentcaptor;
|
||||||
|
|
||||||
public enum Format {
|
public enum Format {
|
||||||
TEXT_ONLY,
|
TEXT_ONLY, HTML
|
||||||
HTML
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,49 +5,49 @@ import java.util.UUID;
|
||||||
|
|
||||||
public class Message {
|
public class Message {
|
||||||
|
|
||||||
private String from;
|
private String from;
|
||||||
private String to;
|
private String to;
|
||||||
private String text;
|
private String text;
|
||||||
private Date date;
|
private Date date;
|
||||||
private UUID id;
|
private UUID id;
|
||||||
|
|
||||||
public String getFrom() {
|
public String getFrom() {
|
||||||
return from;
|
return from;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFrom(String from) {
|
public void setFrom(String from) {
|
||||||
this.from = from;
|
this.from = from;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTo() {
|
public String getTo() {
|
||||||
return to;
|
return to;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTo(String to) {
|
public void setTo(String to) {
|
||||||
this.to = to;
|
this.to = to;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getText() {
|
public String getText() {
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setText(String text) {
|
public void setText(String text) {
|
||||||
this.text = text;
|
this.text = text;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Date getDate() {
|
public Date getDate() {
|
||||||
return date;
|
return date;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDate(Date date) {
|
public void setDate(Date date) {
|
||||||
this.date = date;
|
this.date = date;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UUID getId() {
|
public UUID getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(UUID id) {
|
public void setId(UUID id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,31 +2,31 @@ package com.baeldung.mockito.argumentmatchers;
|
||||||
|
|
||||||
public class MessageDTO {
|
public class MessageDTO {
|
||||||
|
|
||||||
private String from;
|
private String from;
|
||||||
private String to;
|
private String to;
|
||||||
private String text;
|
private String text;
|
||||||
|
|
||||||
public String getFrom() {
|
public String getFrom() {
|
||||||
return from;
|
return from;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFrom(String from) {
|
public void setFrom(String from) {
|
||||||
this.from = from;
|
this.from = from;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTo() {
|
public String getTo() {
|
||||||
return to;
|
return to;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTo(String to) {
|
public void setTo(String to) {
|
||||||
this.to = to;
|
this.to = to;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getText() {
|
public String getText() {
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setText(String text) {
|
public void setText(String text) {
|
||||||
this.text = text;
|
this.text = text;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,16 +13,16 @@ import com.baeldung.mockito.argumentmatchers.service.FlowerService;
|
||||||
@RequestMapping("/flowers")
|
@RequestMapping("/flowers")
|
||||||
public class FlowerController {
|
public class FlowerController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private FlowerService flowerService;
|
private FlowerService flowerService;
|
||||||
|
|
||||||
@PostMapping("/isAFlower")
|
@PostMapping("/isAFlower")
|
||||||
public String isAFlower(@RequestBody String flower) {
|
public String isAFlower(@RequestBody String flower) {
|
||||||
return flowerService.analyze(flower);
|
return flowerService.analyze(flower);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/isABigFlower")
|
@PostMapping("/isABigFlower")
|
||||||
public Boolean isABigFlower(@RequestBody Flower flower) {
|
public Boolean isABigFlower(@RequestBody Flower flower) {
|
||||||
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
|
return flowerService.isABigFlower(flower.getName(), flower.getPetals());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,18 +18,18 @@ import java.util.UUID;
|
||||||
@RequestMapping("/message")
|
@RequestMapping("/message")
|
||||||
public class MessageController {
|
public class MessageController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MessageService messageService;
|
private MessageService messageService;
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public Message createMessage(@RequestBody MessageDTO messageDTO) {
|
public Message createMessage(@RequestBody MessageDTO messageDTO) {
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setText(messageDTO.getText());
|
message.setText(messageDTO.getText());
|
||||||
message.setFrom(messageDTO.getFrom());
|
message.setFrom(messageDTO.getFrom());
|
||||||
message.setTo(messageDTO.getTo());
|
message.setTo(messageDTO.getTo());
|
||||||
message.setDate(Date.from(Instant.now()));
|
message.setDate(Date.from(Instant.now()));
|
||||||
message.setId(UUID.randomUUID());
|
message.setId(UUID.randomUUID());
|
||||||
|
|
||||||
return messageService.deliverMessage(message);
|
return messageService.deliverMessage(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ import com.baeldung.mockito.argumentmatchers.Message;
|
||||||
@Service
|
@Service
|
||||||
public class MessageService {
|
public class MessageService {
|
||||||
|
|
||||||
public Message deliverMessage (Message message) {
|
public Message deliverMessage(Message message) {
|
||||||
|
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,5 +5,5 @@ import com.baeldung.mockito.junit5.User;
|
||||||
public interface MailClient {
|
public interface MailClient {
|
||||||
|
|
||||||
void sendUserRegistrationMail(User user);
|
void sendUserRegistrationMail(User user);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.mockito.junit5.service;
|
||||||
import com.baeldung.mockito.junit5.User;
|
import com.baeldung.mockito.junit5.User;
|
||||||
|
|
||||||
public interface UserService {
|
public interface UserService {
|
||||||
|
|
||||||
User register(User user);
|
User register(User user);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,16 +6,16 @@ import java.util.stream.IntStream;
|
||||||
|
|
||||||
public class StaticUtils {
|
public class StaticUtils {
|
||||||
|
|
||||||
private StaticUtils() {
|
private StaticUtils() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<Integer> range(int start, int end) {
|
public static List<Integer> range(int start, int end) {
|
||||||
return IntStream.range(start, end)
|
return IntStream.range(start, end)
|
||||||
.boxed()
|
.boxed()
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String name() {
|
public static String name() {
|
||||||
return "Baeldung";
|
return "Baeldung";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,9 +2,9 @@ package com.baeldung.mockito;
|
||||||
|
|
||||||
public final class FinalList extends MyList {
|
public final class FinalList extends MyList {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int size() {
|
public int size() {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,21 +5,21 @@ import java.util.Map;
|
||||||
|
|
||||||
public class MyDictionary {
|
public class MyDictionary {
|
||||||
|
|
||||||
private Map<String, String> wordMap;
|
private Map<String, String> wordMap;
|
||||||
|
|
||||||
public MyDictionary() {
|
public MyDictionary() {
|
||||||
wordMap = new HashMap<>();
|
wordMap = new HashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public MyDictionary(Map<String, String> wordMap) {
|
public MyDictionary(Map<String, String> wordMap) {
|
||||||
this.wordMap = wordMap;
|
this.wordMap = wordMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(final String word, final String meaning) {
|
public void add(final String word, final String meaning) {
|
||||||
wordMap.put(word, meaning);
|
wordMap.put(word, meaning);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getMeaning(final String word) {
|
public String getMeaning(final String word) {
|
||||||
return wordMap.get(word);
|
return wordMap.get(word);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,22 +4,22 @@ import java.util.AbstractList;
|
||||||
|
|
||||||
public class MyList extends AbstractList<String> {
|
public class MyList extends AbstractList<String> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String get(final int index) {
|
public String get(final int index) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int size() {
|
public int size() {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void add(int index, String element) {
|
public void add(int index, String element) {
|
||||||
// no-op
|
// no-op
|
||||||
}
|
}
|
||||||
|
|
||||||
final public int finalMethod() {
|
final public int finalMethod() {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,106 +25,106 @@ import com.baeldung.mockito.MyDictionary;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MockitoAnnotationUnitTest {
|
class MockitoAnnotationUnitTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private List<String> mockedList;
|
private List<String> mockedList;
|
||||||
|
|
||||||
@Spy
|
@Spy
|
||||||
private List<String> spiedList = new ArrayList<>();
|
private List<String> spiedList = new ArrayList<>();
|
||||||
|
|
||||||
// Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method
|
// Use either @ExtendWith(MockitoExtension.class) or manually openMocks in the @BeforeEach method
|
||||||
/*
|
/*
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void init() {
|
public void init() {
|
||||||
MockitoAnnotations.openMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseMockAnnotation_thenCorrect() {
|
void whenNotUseMockAnnotation_thenCorrect() {
|
||||||
final List<String> mockList = mock(ArrayList.class);
|
final List<String> mockList = mock(ArrayList.class);
|
||||||
|
|
||||||
mockList.add("one");
|
mockList.add("one");
|
||||||
verify(mockList).add("one");
|
verify(mockList).add("one");
|
||||||
assertEquals(0, mockList.size());
|
assertEquals(0, mockList.size());
|
||||||
|
|
||||||
when(mockList.size()).thenReturn(100);
|
when(mockList.size()).thenReturn(100);
|
||||||
assertEquals(100, mockList.size());
|
assertEquals(100, mockList.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseMockAnnotation_thenMockIsInjected() {
|
void whenUseMockAnnotation_thenMockIsInjected() {
|
||||||
mockedList.add("one");
|
mockedList.add("one");
|
||||||
verify(mockedList).add("one");
|
verify(mockedList).add("one");
|
||||||
assertEquals(0, mockedList.size());
|
assertEquals(0, mockedList.size());
|
||||||
|
|
||||||
when(mockedList.size()).thenReturn(100);
|
when(mockedList.size()).thenReturn(100);
|
||||||
assertEquals(100, mockedList.size());
|
assertEquals(100, mockedList.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseSpyAnnotation_thenCorrect() {
|
void whenNotUseSpyAnnotation_thenCorrect() {
|
||||||
final List<String> spyList = spy(new ArrayList<String>());
|
final List<String> spyList = spy(new ArrayList<String>());
|
||||||
|
|
||||||
spyList.add("one");
|
spyList.add("one");
|
||||||
spyList.add("two");
|
spyList.add("two");
|
||||||
|
|
||||||
verify(spyList).add("one");
|
verify(spyList).add("one");
|
||||||
verify(spyList).add("two");
|
verify(spyList).add("two");
|
||||||
|
|
||||||
assertEquals(2, spyList.size());
|
assertEquals(2, spyList.size());
|
||||||
|
|
||||||
doReturn(100).when(spyList).size();
|
doReturn(100).when(spyList).size();
|
||||||
assertEquals(100, spyList.size());
|
assertEquals(100, spyList.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
|
void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
|
||||||
spiedList.add("one");
|
spiedList.add("one");
|
||||||
spiedList.add("two");
|
spiedList.add("two");
|
||||||
|
|
||||||
verify(spiedList).add("one");
|
verify(spiedList).add("one");
|
||||||
verify(spiedList).add("two");
|
verify(spiedList).add("two");
|
||||||
|
|
||||||
assertEquals(2, spiedList.size());
|
assertEquals(2, spiedList.size());
|
||||||
|
|
||||||
doReturn(100).when(spiedList).size();
|
doReturn(100).when(spiedList).size();
|
||||||
assertEquals(100, spiedList.size());
|
assertEquals(100, spiedList.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotUseCaptorAnnotation_thenCorrect() {
|
void whenNotUseCaptorAnnotation_thenCorrect() {
|
||||||
final List<String> mockList = mock(List.class);
|
final List<String> mockList = mock(List.class);
|
||||||
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
||||||
|
|
||||||
mockList.add("one");
|
mockList.add("one");
|
||||||
verify(mockList).add(arg.capture());
|
verify(mockList).add(arg.capture());
|
||||||
|
|
||||||
assertEquals("one", arg.getValue());
|
assertEquals("one", arg.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Captor
|
@Captor
|
||||||
private ArgumentCaptor<String> argCaptor;
|
private ArgumentCaptor<String> argCaptor;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseCaptorAnnotation_thenTheSame() {
|
void whenUseCaptorAnnotation_thenTheSame() {
|
||||||
mockedList.add("one");
|
mockedList.add("one");
|
||||||
verify(mockedList).add(argCaptor.capture());
|
verify(mockedList).add(argCaptor.capture());
|
||||||
|
|
||||||
assertEquals("one", argCaptor.getValue());
|
assertEquals("one", argCaptor.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private Map<String, String> wordMap;
|
private Map<String, String> wordMap;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private MyDictionary dic = new MyDictionary();
|
private MyDictionary dic = new MyDictionary();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseInjectMocksAnnotation_thenCorrect() {
|
void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||||
when(wordMap.get("aWord")).thenReturn("aMeaning");
|
when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||||
|
|
||||||
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,16 +13,16 @@ import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
|
public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest {
|
||||||
|
|
||||||
@Rule
|
@Rule
|
||||||
public MockitoRule initRule = MockitoJUnit.rule();
|
public MockitoRule initRule = MockitoJUnit.rule();
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private List<String> mockedList;
|
private List<String> mockedList;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
|
public void whenUsingMockitoJUnitRule_thenMocksInitialized() {
|
||||||
when(mockedList.size()).thenReturn(41);
|
when(mockedList.size()).thenReturn(41);
|
||||||
|
|
||||||
assertThat(mockedList).hasSize(41);
|
assertThat(mockedList).hasSize(41);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,24 +19,24 @@ import com.baeldung.mockito.MyDictionary;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MockitoAnnotationsInjectIntoSpyUnitTest {
|
class MockitoAnnotationsInjectIntoSpyUnitTest {
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
public void init() {
|
public void init() {
|
||||||
openMocks(this);
|
openMocks(this);
|
||||||
spyDic = spy(new MyDictionary(wordMap));
|
spyDic = spy(new MyDictionary(wordMap));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private Map<String, String> wordMap;
|
private Map<String, String> wordMap;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private MyDictionary dic = new MyDictionary();
|
private MyDictionary dic = new MyDictionary();
|
||||||
|
|
||||||
private MyDictionary spyDic;
|
private MyDictionary spyDic;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUseInjectMocksAnnotation_thenCorrect() {
|
void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||||
when(wordMap.get("aWord")).thenReturn("aMeaning");
|
when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||||
|
|
||||||
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
|
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,13 +10,13 @@ import org.mockito.Mock;
|
||||||
|
|
||||||
class MockitoAnnotationsUninitializedUnitTest {
|
class MockitoAnnotationsUninitializedUnitTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
List<String> mockedList;
|
List<String> mockedList;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
|
void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
|
||||||
assertThrows(NullPointerException.class, () -> {
|
assertThrows(NullPointerException.class, () -> {
|
||||||
when(mockedList.size()).thenReturn(1);
|
when(mockedList.size()).thenReturn(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,84 +18,84 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class EmailServiceUnitTest {
|
class EmailServiceUnitTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
DeliveryPlatform platform;
|
DeliveryPlatform platform;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
EmailService emailService;
|
EmailService emailService;
|
||||||
|
|
||||||
@Captor
|
@Captor
|
||||||
ArgumentCaptor<Email> emailCaptor;
|
ArgumentCaptor<Email> emailCaptor;
|
||||||
|
|
||||||
@Captor
|
@Captor
|
||||||
ArgumentCaptor<Credentials> credentialsCaptor;
|
ArgumentCaptor<Credentials> credentialsCaptor;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
|
void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
|
||||||
String to = "info@baeldung.com";
|
String to = "info@baeldung.com";
|
||||||
String subject = "Using ArgumentCaptor";
|
String subject = "Using ArgumentCaptor";
|
||||||
String body = "Hey, let'use ArgumentCaptor";
|
String body = "Hey, let'use ArgumentCaptor";
|
||||||
|
|
||||||
emailService.send(to, subject, body, false);
|
emailService.send(to, subject, body, false);
|
||||||
|
|
||||||
verify(platform).deliver(emailCaptor.capture());
|
verify(platform).deliver(emailCaptor.capture());
|
||||||
Email emailCaptorValue = emailCaptor.getValue();
|
Email emailCaptorValue = emailCaptor.getValue();
|
||||||
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
|
assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenDoesSupportHtml_expectHTMLEmailFormat() {
|
void whenDoesSupportHtml_expectHTMLEmailFormat() {
|
||||||
String to = "info@baeldung.com";
|
String to = "info@baeldung.com";
|
||||||
String subject = "Using ArgumentCaptor";
|
String subject = "Using ArgumentCaptor";
|
||||||
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
|
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
|
||||||
|
|
||||||
emailService.send(to, subject, body, true);
|
emailService.send(to, subject, body, true);
|
||||||
|
|
||||||
verify(platform).deliver(emailCaptor.capture());
|
verify(platform).deliver(emailCaptor.capture());
|
||||||
Email value = emailCaptor.getValue();
|
Email value = emailCaptor.getValue();
|
||||||
assertThat(value.getFormat()).isEqualTo(Format.HTML);
|
assertThat(value.getFormat()).isEqualTo(Format.HTML);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenServiceRunning_expectUpResponse() {
|
void whenServiceRunning_expectUpResponse() {
|
||||||
when(platform.getServiceStatus()).thenReturn("OK");
|
when(platform.getServiceStatus()).thenReturn("OK");
|
||||||
|
|
||||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||||
|
|
||||||
assertThat(serviceStatus).isEqualTo(ServiceStatus.UP);
|
assertThat(serviceStatus).isEqualTo(ServiceStatus.UP);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenServiceNotRunning_expectDownResponse() {
|
void whenServiceNotRunning_expectDownResponse() {
|
||||||
when(platform.getServiceStatus()).thenReturn("Error");
|
when(platform.getServiceStatus()).thenReturn("Error");
|
||||||
|
|
||||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||||
|
|
||||||
assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN);
|
assertThat(serviceStatus).isEqualTo(ServiceStatus.DOWN);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
|
void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
|
||||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||||
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||||
|
|
||||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
|
void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
|
||||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||||
when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||||
|
|
||||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||||
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
|
assertThat(credentialsCaptor.getValue()).isEqualTo(credentials);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenNotAuthenticated_expectFalse() {
|
void whenNotAuthenticated_expectFalse() {
|
||||||
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
|
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
|
||||||
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
|
when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
|
||||||
|
|
||||||
assertFalse(emailService.authenticatedSuccessfully(credentials));
|
assertFalse(emailService.authenticatedSuccessfully(credentials));
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -24,57 +24,57 @@ import com.baeldung.mockito.argumentmatchers.service.FlowerService;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class FlowerControllerUnitTest {
|
class FlowerControllerUnitTest {
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private FlowerController flowerController;
|
private FlowerController flowerController;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private FlowerService flowerService;
|
private FlowerService flowerService;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
|
void givenPoppyFlower_whenUsingDoReturn_thenCorrect() {
|
||||||
doReturn("Flower").when(flowerService).analyze("poppy");
|
doReturn("Flower").when(flowerService).analyze("poppy");
|
||||||
|
|
||||||
String response = flowerController.isAFlower("poppy");
|
String response = flowerController.isAFlower("poppy");
|
||||||
assertThat(response).isEqualTo("Flower");
|
assertThat(response).isEqualTo("Flower");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() {
|
void givenAnyFlower_whenUsingArgumentMatcher_thenCorrect() {
|
||||||
when(flowerService.analyze(anyString())).thenReturn("Flower");
|
when(flowerService.analyze(anyString())).thenReturn("Flower");
|
||||||
|
|
||||||
String response = flowerController.isAFlower("violetta");
|
String response = flowerController.isAFlower("violetta");
|
||||||
assertThat(response).isEqualTo("Flower");
|
assertThat(response).isEqualTo("Flower");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() {
|
void givenIncorrectMatchers_whenUsingArgumentMatchers_thenThrowsError() {
|
||||||
assertThrows(InvalidUseOfMatchersException.class,
|
assertThrows(InvalidUseOfMatchersException.class,
|
||||||
() -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true));
|
() -> when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() {
|
void givenCorrectMatchers_whenUsingArgumentMatchers_thenCorrect() {
|
||||||
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
|
when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true);
|
||||||
|
|
||||||
Flower flower = new Flower("poppy", 15);
|
Flower flower = new Flower("poppy", 15);
|
||||||
|
|
||||||
Boolean response = flowerController.isABigFlower(flower);
|
Boolean response = flowerController.isABigFlower(flower);
|
||||||
assertThat(response).isTrue();
|
assertThat(response).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() {
|
void givenMatchersOutsideofStubbing_whenUsingMatchersAsReturnValue_thenThrowsError() {
|
||||||
flowerController.isAFlower("poppy");
|
flowerController.isAFlower("poppy");
|
||||||
|
|
||||||
String orMatcher = or(eq("poppy"), endsWith("y"));
|
String orMatcher = or(eq("poppy"), endsWith("y"));
|
||||||
assertThrows(InvalidUseOfMatchersException.class,
|
assertThrows(InvalidUseOfMatchersException.class,
|
||||||
() -> verify(flowerService).analyze(orMatcher));
|
() -> verify(flowerService).analyze(orMatcher));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() {
|
void givenMatchersAsOngoingStubbing_whenUsingMatchers_thenCorrect() {
|
||||||
flowerController.isAFlower("poppy");
|
flowerController.isAFlower("poppy");
|
||||||
|
|
||||||
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
|
verify(flowerService).analyze(or(eq("poppy"), endsWith("y")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,38 +17,38 @@ import com.baeldung.mockito.argumentmatchers.service.MessageService;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MessageControllerUnitTest {
|
class MessageControllerUnitTest {
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private MessageController messageController;
|
private MessageController messageController;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private MessageService messageService;
|
private MessageService messageService;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
|
void givenMsg_whenVerifyUsingAnyMatcher_thenOk() {
|
||||||
MessageDTO messageDTO = new MessageDTO();
|
MessageDTO messageDTO = new MessageDTO();
|
||||||
messageDTO.setFrom("me");
|
messageDTO.setFrom("me");
|
||||||
messageDTO.setTo("you");
|
messageDTO.setTo("you");
|
||||||
messageDTO.setText("Hello, you!");
|
messageDTO.setText("Hello, you!");
|
||||||
|
|
||||||
messageController.createMessage(messageDTO);
|
messageController.createMessage(messageDTO);
|
||||||
|
|
||||||
verify(messageService, times(1)).deliverMessage(any(Message.class));
|
verify(messageService, times(1)).deliverMessage(any(Message.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
|
void givenMsg_whenVerifyUsingMessageMatcher_thenOk() {
|
||||||
MessageDTO messageDTO = new MessageDTO();
|
MessageDTO messageDTO = new MessageDTO();
|
||||||
messageDTO.setFrom("me");
|
messageDTO.setFrom("me");
|
||||||
messageDTO.setTo("you");
|
messageDTO.setTo("you");
|
||||||
messageDTO.setText("Hello, you!");
|
messageDTO.setText("Hello, you!");
|
||||||
|
|
||||||
messageController.createMessage(messageDTO);
|
messageController.createMessage(messageDTO);
|
||||||
|
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setFrom("me");
|
message.setFrom("me");
|
||||||
message.setTo("you");
|
message.setTo("you");
|
||||||
message.setText("Hello, you!");
|
message.setText("Hello, you!");
|
||||||
|
|
||||||
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
|
verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,10 +12,9 @@ public class MessageMatcher implements ArgumentMatcher<Message> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Message right) {
|
public boolean matches(Message right) {
|
||||||
return left.getFrom().equals(right.getFrom()) &&
|
return left.getFrom().equals(right.getFrom()) &&
|
||||||
left.getTo().equals(right.getTo()) &&
|
left.getTo().equals(right.getTo()) &&
|
||||||
left.getText().equals(right.getText()) &&
|
left.getText().equals(right.getText()) &&
|
||||||
right.getDate() != null &&
|
right.getDate() != null && right.getId() != null;
|
||||||
right.getId() != null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -19,87 +19,87 @@ import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockitoWhenThenExamplesUnitTest {
|
class MockitoWhenThenExamplesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenSimpleReturnBehaviourConfigured_thenCorrect() {
|
final void whenSimpleReturnBehaviourConfigured_thenCorrect() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
|
|
||||||
final boolean added = listMock.add(randomAlphabetic(6));
|
final boolean added = listMock.add(randomAlphabetic(6));
|
||||||
assertThat(added).isFalse();
|
assertThat(added).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() {
|
final void whenSimpleReturnBehaviourConfiguredAlternatively_thenCorrect() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
doReturn(false).when(listMock).add(anyString());
|
doReturn(false).when(listMock).add(anyString());
|
||||||
|
|
||||||
final boolean added = listMock.add(randomAlphabetic(6));
|
final boolean added = listMock.add(randomAlphabetic(6));
|
||||||
assertThat(added).isFalse();
|
assertThat(added).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
|
final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
||||||
|
|
||||||
assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6)));
|
assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() {
|
final void givenMethodHasNoReturnType_whenCallingMethod_thenExceptionIsThrown() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
doThrow(NullPointerException.class).when(listMock).clear();
|
doThrow(NullPointerException.class).when(listMock).clear();
|
||||||
|
|
||||||
assertThrows(NullPointerException.class, () -> listMock.clear());
|
assertThrows(NullPointerException.class, () -> listMock.clear());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
|
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString()))
|
when(listMock.add(anyString()))
|
||||||
.thenReturn(false)
|
.thenReturn(false)
|
||||||
.thenThrow(IllegalStateException.class);
|
.thenThrow(IllegalStateException.class);
|
||||||
|
|
||||||
assertThrows(IllegalStateException.class, () -> {
|
assertThrows(IllegalStateException.class, () -> {
|
||||||
listMock.add(randomAlphabetic(6));
|
listMock.add(randomAlphabetic(6));
|
||||||
listMock.add(randomAlphabetic(6));
|
listMock.add(randomAlphabetic(6));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
|
final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString()))
|
when(listMock.add(anyString()))
|
||||||
.thenReturn(false)
|
.thenReturn(false)
|
||||||
.thenThrow(IllegalStateException.class);
|
.thenThrow(IllegalStateException.class);
|
||||||
|
|
||||||
assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6)));
|
assertThatNoException().isThrownBy(() -> listMock.add(randomAlphabetic(6)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenSpyBehaviourConfigured_thenCorrect() {
|
final void whenSpyBehaviourConfigured_thenCorrect() {
|
||||||
final MyList instance = new MyList();
|
final MyList instance = new MyList();
|
||||||
final MyList spy = spy(instance);
|
final MyList spy = spy(instance);
|
||||||
|
|
||||||
doThrow(NullPointerException.class).when(spy).size();
|
doThrow(NullPointerException.class).when(spy).size();
|
||||||
|
|
||||||
assertThrows(NullPointerException.class, () -> spy.size());
|
assertThrows(NullPointerException.class, () -> spy.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
when(listMock.size()).thenCallRealMethod();
|
when(listMock.size()).thenCallRealMethod();
|
||||||
|
|
||||||
assertThat(listMock).hasSize(1);
|
assertThat(listMock).hasSize(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() {
|
final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenCustomerAnswerIsCalled() {
|
||||||
final MyList listMock = mock(MyList.class);
|
final MyList listMock = mock(MyList.class);
|
||||||
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
||||||
|
|
||||||
final String element = listMock.get(1);
|
final String element = listMock.get(1);
|
||||||
assertThat(element).isEqualTo("Always the same");
|
assertThat(element).isEqualTo("Always the same");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,45 +13,46 @@ import com.baeldung.mockito.MyDictionary;
|
||||||
|
|
||||||
class MockitoExceptionUnitTest {
|
class MockitoExceptionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
void givenNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||||
|
|
||||||
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() {
|
void givenVoidReturnType_whenUsingDoThrow_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
doThrow(IllegalStateException.class).when(dictMock).add(anyString(), anyString());
|
doThrow(IllegalStateException.class).when(dictMock)
|
||||||
|
.add(anyString(), anyString());
|
||||||
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
||||||
void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
}
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
|
||||||
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
|
|
||||||
|
|
||||||
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
void givenNonVoidReturnType_whenUsingWhenThenAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
||||||
MyDictionary dictMock = mock(MyDictionary.class);
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString());
|
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
|
||||||
|
|
||||||
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
|
||||||
|
|
||||||
}
|
assertThrows(NullPointerException.class, () -> dictMock.getMeaning("word"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
void givenNonVoidReturnType_whenUsingDoThrowAndExeceptionAsNewObject_thenExceptionIsThrown() {
|
||||||
MyDictionary dict = new MyDictionary();
|
MyDictionary dictMock = mock(MyDictionary.class);
|
||||||
MyDictionary spy = Mockito.spy(dict);
|
doThrow(new IllegalStateException("Error occurred")).when(dictMock).add(anyString(), anyString());
|
||||||
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> dictMock.add("word", "meaning"));
|
||||||
assertThrows(NullPointerException.class, () -> spy.getMeaning("word"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSpyAndNonVoidReturnType_whenUsingWhenThen_thenExceptionIsThrown() {
|
||||||
|
MyDictionary dict = new MyDictionary();
|
||||||
|
MyDictionary spy = Mockito.spy(dict);
|
||||||
|
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class, () -> spy.getMeaning("word"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,14 +43,14 @@ class UserServiceUnitTest {
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void init(@Mock SettingRepository settingRepository) {
|
void init(@Mock SettingRepository settingRepository) {
|
||||||
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
|
||||||
|
|
||||||
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
|
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
|
||||||
|
|
||||||
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
when(settingRepository.getUserNameMinLength()).thenReturn(4);
|
||||||
|
|
||||||
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
|
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
|
||||||
.thenReturn(false);
|
.thenReturn(false);
|
||||||
|
|
||||||
this.settingRepository = settingRepository;
|
this.settingRepository = settingRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -80,8 +80,8 @@ class UserServiceUnitTest {
|
||||||
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
verify(mailClient).sendUserRegistrationMail(insertedUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
//additional tests
|
// additional tests
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
|
||||||
// Given
|
// Given
|
||||||
|
|
|
@ -11,21 +11,21 @@ import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockFinalsUnitTest {
|
class MockFinalsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenMockFinalMethod_thenMockWorks() {
|
void whenMockFinalMethod_thenMockWorks() {
|
||||||
|
|
||||||
MyList mock = mock(MyList.class);
|
MyList mock = mock(MyList.class);
|
||||||
when(mock.finalMethod()).thenReturn(1);
|
when(mock.finalMethod()).thenReturn(1);
|
||||||
|
|
||||||
assertThat(mock.finalMethod()).isNotZero();
|
assertThat(mock.finalMethod()).isNotZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenMockFinalClass_thenMockWorks() {
|
void whenMockFinalClass_thenMockWorks() {
|
||||||
|
|
||||||
FinalList mock = mock(FinalList.class);
|
FinalList mock = mock(FinalList.class);
|
||||||
when(mock.size()).thenReturn(2);
|
when(mock.size()).thenReturn(2);
|
||||||
|
|
||||||
assertThat(mock.size()).isNotEqualTo(1);
|
assertThat(mock.size()).isNotEqualTo(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,54 +20,54 @@ import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockitoMockMethodsUnitTest {
|
class MockitoMockMethodsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingSimpleMock_thenCorrect() {
|
void whenUsingSimpleMock_thenCorrect() {
|
||||||
MyList listMock = mock(MyList.class);
|
MyList listMock = mock(MyList.class);
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
|
|
||||||
boolean added = listMock.add(randomAlphabetic(6));
|
boolean added = listMock.add(randomAlphabetic(6));
|
||||||
|
|
||||||
assertThat(added).isFalse();
|
assertThat(added).isFalse();
|
||||||
verify(listMock).add(anyString());
|
verify(listMock).add(anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() {
|
void givenFewActualInvocationThanConfigured_whenUsingMockWithName_thenExceptionIsThrown() {
|
||||||
MyList listMock = mock(MyList.class, "myMock");
|
MyList listMock = mock(MyList.class, "myMock");
|
||||||
|
|
||||||
when(listMock.add(anyString())).thenReturn(false);
|
|
||||||
listMock.add(randomAlphabetic(6));
|
|
||||||
|
|
||||||
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
|
when(listMock.add(anyString())).thenReturn(false);
|
||||||
.isInstanceOf(TooFewActualInvocations.class)
|
listMock.add(randomAlphabetic(6));
|
||||||
.hasMessageContaining("myMock.add");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class CustomAnswer implements Answer<Boolean> {
|
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
|
||||||
|
.isInstanceOf(TooFewActualInvocations.class)
|
||||||
@Override
|
.hasMessageContaining("myMock.add");
|
||||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
}
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
private static class CustomAnswer implements Answer<Boolean> {
|
||||||
void whenUsingMockWithAnswer_thenCorrect() {
|
|
||||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
|
||||||
boolean added = listMock.add(randomAlphabetic(6));
|
|
||||||
|
|
||||||
verify(listMock).add(anyString());
|
@Override
|
||||||
assertThat(added).isFalse();
|
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenUsingMockWithSettings_thenCorrect() {
|
void whenUsingMockWithAnswer_thenCorrect() {
|
||||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||||
MyList listMock = mock(MyList.class, customSettings);
|
boolean added = listMock.add(randomAlphabetic(6));
|
||||||
|
|
||||||
boolean added = listMock.add(randomAlphabetic(6));
|
|
||||||
|
|
||||||
verify(listMock).add(anyString());
|
verify(listMock).add(anyString());
|
||||||
assertThat(added).isFalse();
|
assertThat(added).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
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).isFalse();
|
||||||
|
}
|
||||||
}
|
}
|
|
@ -12,30 +12,30 @@ import java.util.Arrays;
|
||||||
|
|
||||||
class MockStaticUnitTest {
|
class MockStaticUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||||
|
|
||||||
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
|
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
|
||||||
utilities.when(StaticUtils::name).thenReturn("Eugen");
|
utilities.when(StaticUtils::name).thenReturn("Eugen");
|
||||||
assertThat(StaticUtils.name()).isEqualTo("Eugen");
|
assertThat(StaticUtils.name()).isEqualTo("Eugen");
|
||||||
}
|
}
|
||||||
|
|
||||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
|
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||||
|
|
||||||
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
|
try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
|
||||||
utilities.when(() -> StaticUtils.range(2, 6))
|
utilities.when(() -> StaticUtils.range(2, 6))
|
||||||
.thenReturn(Arrays.asList(10, 11, 12));
|
.thenReturn(Arrays.asList(10, 11, 12));
|
||||||
|
|
||||||
assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12);
|
assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12);
|
||||||
}
|
}
|
||||||
|
|
||||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,14 +18,14 @@ class MockitoMisusingMockOrSpyUnitTest {
|
||||||
List<String> list = new ArrayList<String>();
|
List<String> list = new ArrayList<String>();
|
||||||
|
|
||||||
assertThatThrownBy(() -> doReturn(100).when(list).size())
|
assertThatThrownBy(() -> doReturn(100).when(list).size())
|
||||||
.isInstanceOf(NotAMockException.class)
|
.isInstanceOf(NotAMockException.class)
|
||||||
.hasMessageContaining("Argument passed to when() is not a mock!");
|
.hasMessageContaining("Argument passed to when() is not a mock!");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenASpy_whenDoReturn_thenNoError() {
|
void givenASpy_whenDoReturn_thenNoError() {
|
||||||
final List<String> spyList = spy(new ArrayList<>());
|
final List<String> spyList = spy(new ArrayList<>());
|
||||||
|
|
||||||
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
|
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,64 +18,64 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class MockitoSpyUnitTest {
|
class MockitoSpyUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
|
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
|
||||||
final List<String> list = new ArrayList<String>();
|
final List<String> list = new ArrayList<String>();
|
||||||
final List<String> spyList = spy(list);
|
final List<String> spyList = spy(list);
|
||||||
|
|
||||||
spyList.add("one");
|
spyList.add("one");
|
||||||
spyList.add("two");
|
spyList.add("two");
|
||||||
|
|
||||||
verify(spyList).add("one");
|
verify(spyList).add("one");
|
||||||
verify(spyList).add("two");
|
verify(spyList).add("two");
|
||||||
|
|
||||||
assertThat(spyList).hasSize(2);
|
assertThat(spyList).hasSize(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Spy
|
@Spy
|
||||||
private List<String> aSpyList = new ArrayList<String>();
|
private List<String> aSpyList = new ArrayList<String>();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
|
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
|
||||||
aSpyList.add("one");
|
aSpyList.add("one");
|
||||||
aSpyList.add("two");
|
aSpyList.add("two");
|
||||||
|
|
||||||
verify(aSpyList).add("one");
|
verify(aSpyList).add("one");
|
||||||
verify(aSpyList).add("two");
|
verify(aSpyList).add("two");
|
||||||
|
|
||||||
assertThat(aSpyList).hasSize(2);
|
assertThat(aSpyList).hasSize(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
|
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
|
||||||
final List<String> list = new ArrayList<String>();
|
final List<String> list = new ArrayList<String>();
|
||||||
final List<String> spyList = spy(list);
|
final List<String> spyList = spy(list);
|
||||||
|
|
||||||
assertEquals(0, spyList.size());
|
assertEquals(0, spyList.size());
|
||||||
|
|
||||||
doReturn(100).when(spyList).size();
|
doReturn(100).when(spyList).size();
|
||||||
|
|
||||||
assertThat(spyList).hasSize(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
assertThat(spyList).hasSize(100);
|
||||||
void whenCreateMock_thenCreated() {
|
}
|
||||||
final List<String> mockedList = mock(ArrayList.class);
|
|
||||||
|
|
||||||
mockedList.add("one");
|
@Test
|
||||||
verify(mockedList).add("one");
|
void whenCreateMock_thenCreated() {
|
||||||
|
final List<String> mockedList = mock(ArrayList.class);
|
||||||
|
|
||||||
assertThat(mockedList).hasSize(0);
|
mockedList.add("one");
|
||||||
}
|
verify(mockedList).add("one");
|
||||||
|
|
||||||
@Test
|
assertThat(mockedList).hasSize(0);
|
||||||
void whenCreateSpy_thenCreate() {
|
}
|
||||||
final List<String> spyList = spy(new ArrayList<>());
|
|
||||||
|
|
||||||
spyList.add("one");
|
@Test
|
||||||
verify(spyList).add("one");
|
void whenCreateSpy_thenCreate() {
|
||||||
|
final List<String> spyList = spy(new ArrayList<>());
|
||||||
|
|
||||||
assertThat(spyList).hasSize(1);
|
spyList.add("one");
|
||||||
}
|
verify(spyList).add("one");
|
||||||
|
|
||||||
|
assertThat(spyList).hasSize(1);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,102 +25,102 @@ import com.google.common.collect.Lists;
|
||||||
|
|
||||||
class MockitoVerifyExamplesUnitTest {
|
class MockitoVerifyExamplesUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() {
|
final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
verify(mockedList).size();
|
verify(mockedList).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() {
|
final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
verify(mockedList, times(1)).size();
|
verify(mockedList, times(1)).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() {
|
final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
verifyNoInteractions(mockedList);
|
verifyNoInteractions(mockedList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() {
|
final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
verify(mockedList, times(0)).size();
|
verify(mockedList, times(0)).size();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
|
final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
|
|
||||||
verify(mockedList).size();
|
verify(mockedList).size();
|
||||||
|
|
||||||
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));
|
assertThrows(NoInteractionsWanted.class, () -> verifyNoMoreInteractions(mockedList));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() {
|
final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
mockedList.add("a parameter");
|
mockedList.add("a parameter");
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
|
|
||||||
final InOrder inOrder = inOrder(mockedList);
|
final InOrder inOrder = inOrder(mockedList);
|
||||||
inOrder.verify(mockedList).size();
|
inOrder.verify(mockedList).size();
|
||||||
inOrder.verify(mockedList).add("a parameter");
|
inOrder.verify(mockedList).add("a parameter");
|
||||||
inOrder.verify(mockedList).clear();
|
inOrder.verify(mockedList).clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() {
|
final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.size();
|
mockedList.size();
|
||||||
|
|
||||||
verify(mockedList, never()).clear();
|
verify(mockedList, never()).clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() {
|
final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
mockedList.clear();
|
mockedList.clear();
|
||||||
|
|
||||||
verify(mockedList, atLeast(1)).clear();
|
verify(mockedList, atLeast(1)).clear();
|
||||||
verify(mockedList, atMost(10)).clear();
|
verify(mockedList, atMost(10)).clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// with arguments
|
// with arguments
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() {
|
final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.add("test");
|
mockedList.add("test");
|
||||||
|
|
||||||
verify(mockedList).add("test");
|
verify(mockedList).add("test");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() {
|
final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.add("test");
|
mockedList.add("test");
|
||||||
|
|
||||||
verify(mockedList).add(anyString());
|
verify(mockedList).add(anyString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
||||||
final List<String> mockedList = mock(MyList.class);
|
final List<String> mockedList = mock(MyList.class);
|
||||||
mockedList.addAll(Lists.<String> newArrayList("someElement"));
|
mockedList.addAll(Lists.<String> newArrayList("someElement"));
|
||||||
|
|
||||||
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
final ArgumentCaptor<List<String>> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
||||||
verify(mockedList).addAll(argumentCaptor.capture());
|
verify(mockedList).addAll(argumentCaptor.capture());
|
||||||
|
|
||||||
final List<String> capturedArgument = argumentCaptor.getValue();
|
final List<String> capturedArgument = argumentCaptor.getValue();
|
||||||
assertThat(capturedArgument).contains("someElement");
|
assertThat(capturedArgument).contains("someElement");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,69 +20,71 @@ import com.baeldung.mockito.MyList;
|
||||||
|
|
||||||
class MockitoVoidMethodsUnitTest {
|
class MockitoVoidMethodsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenAddCalled_thenVerified() {
|
void whenAddCalled_thenVerified() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
doNothing().when(myList).add(isA(Integer.class), isA(String.class));
|
doNothing().when(myList).add(isA(Integer.class), isA(String.class));
|
||||||
myList.add(0, "");
|
myList.add(0, "");
|
||||||
|
|
||||||
verify(myList, times(1)).add(0, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void whenAddCalled_thenVerified2() {
|
|
||||||
MyList myList = mock(MyList.class);
|
|
||||||
myList.add(0, "");
|
|
||||||
|
|
||||||
verify(myList, times(1)).add(0, "");
|
verify(myList, times(1)).add(0, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenNull_whenAddCalled_thenThrowsException() {
|
void whenAddCalled_thenVerified2() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
|
myList.add(0, "");
|
||||||
assertThrows(Exception.class, () -> {
|
|
||||||
doThrow().when(myList).add(isA(Integer.class), isNull());
|
|
||||||
});
|
|
||||||
|
|
||||||
myList.add(0, null);
|
verify(myList, times(1)).add(0, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenArgumentCaptor_whenAddCalled_thenValueCaptured() {
|
void givenNull_whenAddCalled_thenThrowsException() {
|
||||||
MyList myList = mock(MyList.class);
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
|
||||||
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
|
|
||||||
|
|
||||||
myList.add(0, "captured");
|
|
||||||
|
|
||||||
assertEquals("captured", valueCapture.getValue());
|
assertThrows(Exception.class, () -> {
|
||||||
}
|
doThrow().when(myList).add(isA(Integer.class), isNull());
|
||||||
|
});
|
||||||
|
|
||||||
@Test
|
myList.add(0, null);
|
||||||
void givenDoAnswer_whenAddCalled_thenAnswered() {
|
}
|
||||||
MyList myList = mock(MyList.class);
|
|
||||||
|
|
||||||
doAnswer(invocation -> {
|
@Test
|
||||||
Object arg0 = invocation.getArgument(0);
|
void givenArgumentCaptor_whenAddCalled_thenValueCaptured() {
|
||||||
Object arg1 = invocation.getArgument(1);
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
assertEquals(3, arg0);
|
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
||||||
assertEquals("answer me", arg1);
|
doNothing().when(myList).add(any(Integer.class), valueCapture.capture());
|
||||||
return null;
|
|
||||||
}).when(myList).add(any(Integer.class), any(String.class));
|
|
||||||
|
|
||||||
myList.add(3, "answer me");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
myList.add(0, "captured");
|
||||||
void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() {
|
|
||||||
MyList myList = mock(MyList.class);
|
|
||||||
|
|
||||||
doCallRealMethod().when(myList).add(any(Integer.class), any(String.class));
|
|
||||||
myList.add(1, "real");
|
|
||||||
|
|
||||||
verify(myList, times(1)).add(1, "real");
|
assertEquals("captured", valueCapture.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDoAnswer_whenAddCalled_thenAnswered() {
|
||||||
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
Object arg0 = invocation.getArgument(0);
|
||||||
|
Object arg1 = invocation.getArgument(1);
|
||||||
|
|
||||||
|
assertEquals(3, arg0);
|
||||||
|
assertEquals("answer me", arg1);
|
||||||
|
return null;
|
||||||
|
}).when(myList)
|
||||||
|
.add(any(Integer.class), any(String.class));
|
||||||
|
|
||||||
|
myList.add(3, "answer me");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled() {
|
||||||
|
MyList myList = mock(MyList.class);
|
||||||
|
|
||||||
|
doCallRealMethod().when(myList)
|
||||||
|
.add(any(Integer.class), any(String.class));
|
||||||
|
myList.add(1, "real");
|
||||||
|
|
||||||
|
verify(myList, times(1)).add(1, "real");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue