diff --git a/testing-modules/mockito-simple/pom.xml b/testing-modules/mockito-simple/pom.xml index f96cb98d46..30928cfe35 100644 --- a/testing-modules/mockito-simple/pom.xml +++ b/testing-modules/mockito-simple/pom.xml @@ -29,14 +29,12 @@ spring-context ${spring-framework.version} - org.apache.commons commons-lang3 ${commons-lang3.version} - org.mockito diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java index 3ec86b4499..598c7c93fa 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java @@ -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; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java index 4c10375159..50363d7c17 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java @@ -1,6 +1,5 @@ package com.baeldung.mockito.argumentcaptor; public enum Format { - TEXT_ONLY, - HTML + TEXT_ONLY, HTML } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java index 13d285de8d..60ddc5ac04 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/Message.java @@ -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; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java index 76989e758c..7dce0ab75b 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/MessageDTO.java @@ -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; + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java index 29c8dbb15d..e0c7cfb62e 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/FlowerController.java @@ -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()); + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java index 16eb041044..4a6cb3f5d6 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/controller/MessageController.java @@ -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); + } } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java index beeccf763a..3f9265db0e 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/argumentmatchers/service/MessageService.java @@ -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; } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java index 722c4fff71..258de77cd5 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/repository/MailClient.java @@ -5,5 +5,5 @@ import com.baeldung.mockito.junit5.User; public interface MailClient { void sendUserRegistrationMail(User user); - + } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java index b781747a45..fe1fbe4f13 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/junit5/service/UserService.java @@ -3,7 +3,7 @@ package com.baeldung.mockito.junit5.service; import com.baeldung.mockito.junit5.User; public interface UserService { - + User register(User user); } diff --git a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java index e7ee3a0aa6..5b2e57ae26 100644 --- a/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java +++ b/testing-modules/mockito-simple/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java @@ -6,16 +6,16 @@ import java.util.stream.IntStream; public class StaticUtils { - private StaticUtils() { - } + private StaticUtils() { + } - public static List range(int start, int end) { - return IntStream.range(start, end) - .boxed() - .collect(Collectors.toList()); - } + public static List 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"; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java index 87e8b5de77..c81e0bb79b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/FinalList.java @@ -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; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java index 6877d7fb6a..bb7b076ea6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyDictionary.java @@ -5,21 +5,21 @@ import java.util.Map; public class MyDictionary { - private Map wordMap; + private Map wordMap; - public MyDictionary() { - wordMap = new HashMap<>(); - } + public MyDictionary() { + wordMap = new HashMap<>(); + } - public MyDictionary(Map wordMap) { - this.wordMap = wordMap; - } + public MyDictionary(Map 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); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java index 8324af8ae8..ac3a76e04a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MyList.java @@ -4,22 +4,22 @@ import java.util.AbstractList; public class MyList extends AbstractList { - @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; + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java index 5e12b5c34a..20c70ce27b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java @@ -25,106 +25,106 @@ import com.baeldung.mockito.MyDictionary; @ExtendWith(MockitoExtension.class) class MockitoAnnotationUnitTest { - @Mock - private List mockedList; + @Mock + private List mockedList; - @Spy - private List spiedList = new ArrayList<>(); + @Spy + private List 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 mockList = mock(ArrayList.class); + @Test + void whenNotUseMockAnnotation_thenCorrect() { + final List 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 spyList = spy(new ArrayList()); + @Test + void whenNotUseSpyAnnotation_thenCorrect() { + final List spyList = spy(new ArrayList()); - 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 mockList = mock(List.class); - final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); + @Test + void whenNotUseCaptorAnnotation_thenCorrect() { + final List mockList = mock(List.class); + final ArgumentCaptor 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 argCaptor; + @Captor + private ArgumentCaptor 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 wordMap; + @Mock + private Map 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")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java index 437462fcb4..b8dadc6deb 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java @@ -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 mockedList; + @Mock + private List 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); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java index 44b8d5ec8f..91dd30a20b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsInjectIntoSpyUnitTest.java @@ -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 wordMap; + @Mock + private Map 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")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java index 1b7db32c37..7c317c6aca 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationsUninitializedUnitTest.java @@ -10,13 +10,13 @@ import org.mockito.Mock; class MockitoAnnotationsUninitializedUnitTest { - @Mock - List mockedList; + @Mock + List 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); + }); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index a0d542e152..36c26659a6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -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 emailCaptor; + @Captor + ArgumentCaptor emailCaptor; - @Captor - ArgumentCaptor credentialsCaptor; + @Captor + ArgumentCaptor 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 = "Hey, let'use ArgumentCaptor"; + @Test + void whenDoesSupportHtml_expectHTMLEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; - 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)); + } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java index 5db7f2e112..e9dcc4a774 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/FlowerControllerUnitTest.java @@ -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"))); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java index 5a64f37696..89548c9a99 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageControllerUnitTest.java @@ -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))); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java index e50c8ac9d7..8834df6c38 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentmatchers/MessageMatcher.java @@ -12,10 +12,9 @@ public class MessageMatcher implements ArgumentMatcher { @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; } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java index 4fd70007ab..c4551f43ec 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/behaviour/MockitoWhenThenExamplesUnitTest.java @@ -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"); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java index b612749328..112a6fd7b6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/exceptions/MockitoExceptionUnitTest.java @@ -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")); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java index 461e377a39..45eb42a00f 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/junit5/UserServiceUnitTest.java @@ -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 diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java index 10fd480015..705f2ac7ad 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockfinal/MockFinalsUnitTest.java @@ -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); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java index 0a113ed143..696208c9ec 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockmethods/MockitoMockMethodsUnitTest.java @@ -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 { - - @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 { - 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(); + } } \ No newline at end of file diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java index 0d653940a4..b9268f3c6a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockstatic/MockStaticUnitTest.java @@ -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 utilities = mockStatic(StaticUtils.class)) { - utilities.when(StaticUtils::name).thenReturn("Eugen"); - assertThat(StaticUtils.name()).isEqualTo("Eugen"); - } + try (MockedStatic 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 utilities = mockStatic(StaticUtils.class)) { - utilities.when(() -> StaticUtils.range(2, 6)) - .thenReturn(Arrays.asList(10, 11, 12)); + try (MockedStatic 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); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java index e1023c5e57..0a510ba6cb 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java @@ -18,14 +18,14 @@ class MockitoMisusingMockOrSpyUnitTest { List list = new ArrayList(); 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 spyList = spy(new ArrayList<>()); - + assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size()); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java index d154044191..400de07886 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java @@ -18,64 +18,64 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class MockitoSpyUnitTest { - @Test - void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() { - final List list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() { + final List list = new ArrayList(); + final List 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 aSpyList = new ArrayList(); + @Spy + private List aSpyList = new ArrayList(); - @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 list = new ArrayList(); - final List spyList = spy(list); + @Test + void givenASpy_whenStubbingTheBehaviour_thenCorrect() { + final List list = new ArrayList(); + final List 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 mockedList = mock(ArrayList.class); + assertThat(spyList).hasSize(100); + } - mockedList.add("one"); - verify(mockedList).add("one"); + @Test + void whenCreateMock_thenCreated() { + final List mockedList = mock(ArrayList.class); - assertThat(mockedList).hasSize(0); - } + mockedList.add("one"); + verify(mockedList).add("one"); - @Test - void whenCreateSpy_thenCreate() { - final List spyList = spy(new ArrayList<>()); + assertThat(mockedList).hasSize(0); + } - spyList.add("one"); - verify(spyList).add("one"); + @Test + void whenCreateSpy_thenCreate() { + final List spyList = spy(new ArrayList<>()); - assertThat(spyList).hasSize(1); - } + spyList.add("one"); + verify(spyList).add("one"); + + assertThat(spyList).hasSize(1); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java index 383231b458..902bad33f5 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/verify/MockitoVerifyExamplesUnitTest.java @@ -25,102 +25,102 @@ import com.google.common.collect.Lists; class MockitoVerifyExamplesUnitTest { - @Test - final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList).size(); - } + @Test + final void givenInteractionWithMock_whenVerifyingInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList).size(); + } - @Test - final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.size(); - verify(mockedList, times(1)).size(); - } + @Test + final void givenOneInteractionWithMock_whenVerifyingNumberOfInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); + verify(mockedList, times(1)).size(); + } - @Test - final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verifyNoInteractions(mockedList); - } + @Test + final void givenNoInteractionWithWholeMock_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verifyNoInteractions(mockedList); + } - @Test - final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() { - final List mockedList = mock(MyList.class); - verify(mockedList, times(0)).size(); - } + @Test + final void givenNoInteractionWithSpecificMethod_whenVerifyingInteractions_thenCorrect() { + final List mockedList = mock(MyList.class); + verify(mockedList, times(0)).size(); + } - @Test - final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { - final List mockedList = mock(MyList.class); - mockedList.size(); - mockedList.clear(); + @Test + final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { + final List 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 mockedList = mock(MyList.class); - mockedList.size(); - mockedList.add("a parameter"); - mockedList.clear(); + @Test + final void givenInteractionsInOrder_whenVerifyingOrderOfInteractions_thenCorrect() { + final List 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 mockedList = mock(MyList.class); - mockedList.size(); + @Test + final void givenNoInteraction_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.size(); - verify(mockedList, never()).clear(); - } + verify(mockedList, never()).clear(); + } - @Test - final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.clear(); - mockedList.clear(); - mockedList.clear(); + @Test + final void givenInteractionAtLeastOnce_whenVerifyingAnInteraction_thenCorrect() { + final List 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 mockedList = mock(MyList.class); - mockedList.add("test"); + @Test + final void givenInteractionWithExactArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); - verify(mockedList).add("test"); - } + verify(mockedList).add("test"); + } - @Test - final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.add("test"); + @Test + final void givenInteractionWithAnyArgument_whenVerifyingAnInteraction_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.add("test"); - verify(mockedList).add(anyString()); - } + verify(mockedList).add(anyString()); + } - @Test - final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { - final List mockedList = mock(MyList.class); - mockedList.addAll(Lists. newArrayList("someElement")); + @Test + final void givenInteraction_whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { + final List mockedList = mock(MyList.class); + mockedList.addAll(Lists. newArrayList("someElement")); - final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); - verify(mockedList).addAll(argumentCaptor.capture()); + final ArgumentCaptor> argumentCaptor = ArgumentCaptor.forClass(List.class); + verify(mockedList).addAll(argumentCaptor.capture()); - final List capturedArgument = argumentCaptor.getValue(); - assertThat(capturedArgument).contains("someElement"); - } + final List capturedArgument = argumentCaptor.getValue(); + assertThat(capturedArgument).contains("someElement"); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java index ef4f91139d..ee8c36435a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java @@ -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 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 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"); + } }