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