JAVA-13336 Refactor mockito modules (#12517)

* JAVA-13336 Refactor mockito modules

* JAVA-13336 Fix Jenkins build
This commit is contained in:
anuragkumawat
2022-07-21 23:10:50 +05:30
committed by GitHub
parent baeaf4335f
commit b23fcdc4c4
44 changed files with 24 additions and 141 deletions
@@ -1,58 +0,0 @@
package com.baeldung.mockito.additionalanswers;
public class Book {
private Long bookId;
private String title;
private String author;
private int numberOfPages;
public Book(String title, String author, int numberOfPages) {
this.title = title;
this.author = author;
this.numberOfPages = numberOfPages;
}
public Book(Long bookId, String title, String author, int numberOfPages) {
this.bookId = bookId;
this.title = title;
this.author = author;
this.numberOfPages = numberOfPages;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
}
}
@@ -1,24 +0,0 @@
package com.baeldung.mockito.additionalanswers;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BookRepository {
public Book getByBookId(Long bookId) {
return new Book(bookId, "To Kill a Mocking Bird", "Harper Lee", 256);
}
public Book save(Book book) {
return new Book(book.getBookId(), book.getTitle(), book.getAuthor(), book.getNumberOfPages());
}
public Book selectRandomBook(Book bookOne, Book bookTwo, Book bookThree) {
List<Book> selection = new ArrayList<>();
selection.add(bookOne);
selection.add(bookTwo);
selection.add(bookThree);
Random random = new Random();
return selection.get(random.nextInt(selection.size()));
}
}
@@ -1,22 +0,0 @@
package com.baeldung.mockito.additionalanswers;
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public Book getByBookId(Long id) {
return bookRepository.getByBookId(id);
}
public Book save(Book book) {
return bookRepository.save(book);
}
public Book selectRandomBook(Book book1, Book book2, Book book3) {
return bookRepository.selectRandomBook(book1, book2, book3);
}
}
@@ -1,102 +0,0 @@
package com.baeldung.mockito.fluentapi;
import java.util.ArrayList;
import java.util.List;
public class Pizza {
public enum PizzaSize {
LARGE, MEDIUM, SMALL;
}
private String name;
private PizzaSize size;
private List<String> toppings;
private boolean stuffedCrust;
private boolean collect;
private Integer discount;
private Pizza(PizzaBuilder builder) {
this.name = builder.name;
this.size = builder.size;
this.toppings = builder.toppings;
this.stuffedCrust = builder.stuffedCrust;
this.collect = builder.collect;
this.discount = builder.discount;
}
public String getName() {
return name;
}
public PizzaSize getSize() {
return size;
}
public List<String> getToppings() {
return toppings;
}
public boolean isStuffedCrust() {
return stuffedCrust;
}
public boolean isCollecting() {
return collect;
}
public Integer getDiscount() {
return discount;
}
public static class PizzaBuilder {
private String name;
private PizzaSize size;
private List<String> toppings;
private boolean stuffedCrust;
private boolean collect;
private Integer discount = null;
public PizzaBuilder() {
}
public PizzaBuilder name(String name) {
this.name = name;
return this;
}
public PizzaBuilder size(PizzaSize size) {
this.size = size;
return this;
}
public PizzaBuilder withExtraTopping(String extraTopping) {
if (this.toppings == null) {
toppings = new ArrayList<>();
}
this.toppings.add(extraTopping);
return this;
}
public PizzaBuilder withStuffedCrust(boolean stuffedCrust) {
this.stuffedCrust = stuffedCrust;
return this;
}
public PizzaBuilder willCollect(boolean collect) {
this.collect = collect;
return this;
}
public PizzaBuilder applyDiscount(Integer discount) {
this.discount = discount;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
}
@@ -1,23 +0,0 @@
package com.baeldung.mockito.fluentapi;
import com.baeldung.mockito.fluentapi.Pizza.PizzaSize;
public class PizzaService {
private Pizza.PizzaBuilder builder;
public PizzaService(Pizza.PizzaBuilder builder) {
this.builder = builder;
}
public Pizza orderHouseSpecial() {
return builder.name("Special")
.size(PizzaSize.LARGE)
.withExtraTopping("Mushrooms")
.withStuffedCrust(true)
.withExtraTopping("Chilli")
.willCollect(true)
.applyDiscount(20)
.build();
}
}
@@ -1,20 +0,0 @@
package com.baeldung.mockito.java8;
public class JobPosition {
private String title;
public JobPosition() {}
public JobPosition(String title) {
super();
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@@ -1,20 +0,0 @@
package com.baeldung.mockito.java8;
import java.util.Optional;
import java.util.stream.Stream;
public interface JobService {
Optional<JobPosition> findCurrentJobPosition(Person person);
default boolean assignJobPosition(Person person, JobPosition jobPosition) {
if (!findCurrentJobPosition(person).isPresent()) {
person.setCurrentJobPosition(jobPosition);
return true;
} else {
return false;
}
}
Stream<JobPosition> listJobs(Person person);
}
@@ -1,28 +0,0 @@
package com.baeldung.mockito.java8;
public class Person {
private String name;
private JobPosition currentJobPosition;
public Person() {}
public Person(String name) {
this.name = name;
}
public JobPosition getCurrentJobPosition() {
return currentJobPosition;
}
public void setCurrentJobPosition(JobPosition currentJobPosition) {
this.currentJobPosition = currentJobPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -1,11 +0,0 @@
package com.baeldung.mockito.java8;
import java.util.Optional;
public interface UnemploymentService {
boolean personIsEntitledToUnemploymentSupport(Person person);
Optional<JobPosition> searchJob(Person person, String searchString);
}
@@ -1,26 +0,0 @@
package com.baeldung.mockito.java8;
import java.util.Optional;
import java.util.stream.Stream;
public class UnemploymentServiceImpl implements UnemploymentService {
private final JobService jobService;
public UnemploymentServiceImpl(JobService jobService) {
this.jobService = jobService;
}
@Override
public boolean personIsEntitledToUnemploymentSupport(Person person) {
Optional<JobPosition> optional = jobService.findCurrentJobPosition(person);
return !optional.isPresent();
}
@Override
public Optional<JobPosition> searchJob(Person person, String searchString) {
Stream<JobPosition> stream = jobService.listJobs(person);
return stream.filter((j) -> j.getTitle().contains(searchString)).findFirst();
}
}
@@ -1,15 +0,0 @@
package com.baeldung.mockito.mocksettings;
public abstract class AbstractCoffee {
protected String name;
protected AbstractCoffee(String name) {
this.name = name;
}
protected String getName() {
return name;
}
}
@@ -1,10 +0,0 @@
package com.baeldung.mockito.mocksettings;
public class SimpleService {
public SimpleService(SpecialInterface special) {
Runnable runnable = (Runnable) special;
runnable.run();
}
}
@@ -1,5 +0,0 @@
package com.baeldung.mockito.mocksettings;
public interface SpecialInterface {
}
@@ -1,32 +0,0 @@
package com.baeldung.mockito.objectmapper;
public class Flower {
private String name;
private Integer petals;
public Flower(String name, Integer petals) {
this.name = name;
this.petals = petals;
}
public Flower() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPetals() {
return petals;
}
public void setPetals(Integer petals) {
this.petals = petals;
}
}
@@ -1,17 +0,0 @@
package com.baeldung.mockito.objectmapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FlowerJsonStringValidator {
private ObjectMapper objectMapper;
public FlowerJsonStringValidator(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public boolean flowerHasPetals(String jsonFlowerAsString) throws JsonProcessingException {
Flower flower = objectMapper.readValue(jsonFlowerAsString, Flower.class);
return flower.getPetals() > 0;
}
}
@@ -1,11 +0,0 @@
package com.baeldung.mockito.whenvsdomethods;
import java.time.DayOfWeek;
public interface Employee {
String greet();
void work(DayOfWeek day);
}
@@ -1,5 +0,0 @@
package com.baeldung.mockito.whenvsdomethods;
public class IAmOnHolidayException extends RuntimeException {
}
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -1,104 +0,0 @@
package com.baeldung.mockito.additionalanswers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.AdditionalAnswers.answer;
import static org.mockito.AdditionalAnswers.answerVoid;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BookServiceUnitTest {
@InjectMocks
private BookService bookService;
@Mock
private BookRepository bookRepository;
@Test
public void givenSaveMethodMocked_whenSaveInvoked_ThenReturnFirstArgument_UnitTest() {
Book book = new Book("To Kill a Mocking Bird", "Harper Lee", 256);
Mockito.when(bookRepository.save(any(Book.class))).then(AdditionalAnswers.returnsFirstArg());
Book savedBook = bookService.save(book);
assertEquals(savedBook, book);
}
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnSecondArgument_UnitTest() {
Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456);
Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300);
Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200);
Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg());
Book secondBook = bookService.selectRandomBook(book1, book2, book3);
assertEquals(secondBook, book2);
}
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnLastArgument_UnitTest() {
Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456);
Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300);
Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200);
Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg());
Book lastBook = bookService.selectRandomBook(book1, book2, book3);
assertEquals(lastBook, book3);
}
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnArgumentAtIndex_UnitTest() {
Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456);
Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300);
Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200);
Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1));
Book bookOnIndex = bookService.selectRandomBook(book1, book2, book3);
assertEquals(bookOnIndex, book2);
}
@Test
public void givenMockedMethod_whenMethodInvoked_thenReturnBook() {
Long id = 1L;
when(bookRepository.getByBookId(anyLong())).thenAnswer(answer(BookServiceUnitTest::buildBook));
assertNotNull(bookService.getByBookId(id));
assertEquals("The Stranger", bookService.getByBookId(id).getTitle());
}
@Test
public void givenMockedMethod_whenMethodInvoked_thenReturnVoid() {
Long id = 2L;
when(bookRepository.getByBookId(anyLong())).thenAnswer(answerVoid(BookServiceUnitTest::printBookId));
bookService.getByBookId(id);
verify(bookRepository, times(1)).getByBookId(id);
}
private static Book buildBook(Long bookId) {
return new Book(bookId, "The Stranger", "Albert Camus", 456);
}
private static void printBookId(Long bookId) {
System.out.println(bookId);
}
}
@@ -1,104 +0,0 @@
package com.baeldung.mockito.bddmockito;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.*;
public class BDDMockitoUnitTest {
PhoneBookService phoneBookService;
PhoneBookRepository phoneBookRepository;
String momContactName = "Mom";
String momPhoneNumber = "01234";
String xContactName = "x";
String tooLongPhoneNumber = "01111111111111";
@Before
public void init() {
phoneBookRepository = Mockito.mock(PhoneBookRepository.class);
phoneBookService = new PhoneBookService(phoneBookRepository);
}
@Test
public void givenValidContactName_whenSearchInPhoneBook_thenRetunPhoneNumber() {
given(phoneBookRepository.contains(momContactName)).willReturn(true);
given(phoneBookRepository.getPhoneNumberByContactName(momContactName))
.will((InvocationOnMock invocation) -> {
if(invocation.getArgument(0).equals(momContactName)) {
return momPhoneNumber;
} else {
return null;
}
});
String phoneNumber = phoneBookService.search(momContactName);
then(phoneBookRepository).should().contains(momContactName);
then(phoneBookRepository).should().getPhoneNumberByContactName(momContactName);
Assert.assertEquals(phoneNumber, momPhoneNumber);
}
@Test
public void givenInvalidContactName_whenSearch_thenRetunNull() {
given(phoneBookRepository.contains(xContactName)).willReturn(false);
String phoneNumber = phoneBookService.search(xContactName);
then(phoneBookRepository).should().contains(xContactName);
then(phoneBookRepository).should(never()).getPhoneNumberByContactName(xContactName);
Assert.assertEquals(phoneNumber, null);
}
@Test
public void givenValidContactNameAndPhoneNumber_whenRegister_thenSucceed() {
given(phoneBookRepository.contains(momContactName)).willReturn(false);
phoneBookService.register(momContactName, momPhoneNumber);
verify(phoneBookRepository).insert(momContactName, momPhoneNumber);
}
@Test
public void givenEmptyPhoneNumber_whenRegister_thenFail() {
given(phoneBookRepository.contains(momContactName)).willReturn(false);
phoneBookService.register(xContactName, "");
then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber);
}
@Test
public void givenLongPhoneNumber_whenRegister_thenFail() {
given(phoneBookRepository.contains(xContactName)).willReturn(false);
willThrow(new RuntimeException())
.given(phoneBookRepository).insert(any(String.class), eq(tooLongPhoneNumber));
try {
phoneBookService.register(xContactName, tooLongPhoneNumber);
fail("Should throw exception");
} catch (RuntimeException ex) { }
then(phoneBookRepository).should(never()).insert(momContactName, tooLongPhoneNumber);
}
@Test
public void givenExistentContactName_whenRegister_thenFail() {
given(phoneBookRepository.contains(momContactName))
.willThrow(new RuntimeException("Name already exist"));
try {
phoneBookService.register(momContactName, momPhoneNumber);
fail("Should throw exception");
} catch(Exception ex) { }
then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber);
}
}
@@ -1,26 +0,0 @@
package com.baeldung.mockito.bddmockito;
public interface PhoneBookRepository {
/**
* Insert phone record
* @param name Contact name
* @param phone Phone number
*/
void insert(String name, String phone);
/**
* Search for contact phone number
* @param name Contact name
* @return phone number
*/
String getPhoneNumberByContactName(String name);
/**
* Check if the phonebook contains this contact
* @param name Contact name
* @return true if this contact name exists
*/
boolean contains(String name);
}
@@ -1,34 +0,0 @@
package com.baeldung.mockito.bddmockito;
public class PhoneBookService {
private PhoneBookRepository phoneBookRepository;
public PhoneBookService(PhoneBookRepository phoneBookRepository) {
this.phoneBookRepository = phoneBookRepository;
}
/**
* Register a contact
* @param name Contact name
* @param phone Phone number
*/
public void register(String name, String phone) {
if(!name.isEmpty() && !phone.isEmpty() && !phoneBookRepository.contains(name)) {
phoneBookRepository.insert(name, phone);
}
}
/**
* Search for a phone number by contact name
* @param name Contact name
* @return Phone number
*/
public String search(String name) {
if(!name.isEmpty() && phoneBookRepository.contains(name)) {
return phoneBookRepository.getPhoneNumberByContactName(name);
}
return null;
}
}
@@ -1,83 +0,0 @@
package com.baeldung.mockito.fluentapi;
import com.baeldung.mockito.fluentapi.Pizza.PizzaBuilder;
import com.baeldung.mockito.fluentapi.Pizza.PizzaSize;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PizzaServiceUnitTest {
@Mock
private Pizza expectedPizza;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private PizzaBuilder anotherbuilder;
@Captor
private ArgumentCaptor<String> stringCaptor;
@Captor
private ArgumentCaptor<Pizza.PizzaSize> sizeCaptor;
@Test
public void givenTraditonalMocking_whenServiceInvoked_thenPizzaIsBuilt() {
PizzaBuilder nameBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder sizeBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder firstToppingBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder secondToppingBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder stuffedBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder willCollectBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder discountBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
PizzaBuilder builder = Mockito.mock(Pizza.PizzaBuilder.class);
when(builder.name(anyString())).thenReturn(nameBuilder);
when(nameBuilder.size(any(Pizza.PizzaSize.class))).thenReturn(sizeBuilder);
when(sizeBuilder.withExtraTopping(anyString())).thenReturn(firstToppingBuilder);
when(firstToppingBuilder.withStuffedCrust(anyBoolean())).thenReturn(stuffedBuilder);
when(stuffedBuilder.withExtraTopping(anyString())).thenReturn(secondToppingBuilder);
when(secondToppingBuilder.willCollect(anyBoolean())).thenReturn(willCollectBuilder);
when(willCollectBuilder.applyDiscount(anyInt())).thenReturn(discountBuilder);
when(discountBuilder.build()).thenReturn(expectedPizza);
PizzaService service = new PizzaService(builder);
assertEquals("Expected Pizza", expectedPizza, service.orderHouseSpecial());
verify(builder).name(stringCaptor.capture());
assertEquals("Pizza name: ", "Special", stringCaptor.getValue());
verify(nameBuilder).size(sizeCaptor.capture());
assertEquals("Pizza size: ", PizzaSize.LARGE, sizeCaptor.getValue());
}
@Test
public void givenDeepStubs_whenServiceInvoked_thenPizzaIsBuilt() {
Mockito.when(anotherbuilder.name(anyString())
.size(any(Pizza.PizzaSize.class))
.withExtraTopping(anyString())
.withStuffedCrust(anyBoolean())
.withExtraTopping(anyString())
.willCollect(anyBoolean())
.applyDiscount(anyInt())
.build())
.thenReturn(expectedPizza);
PizzaService service = new PizzaService(anotherbuilder);
assertEquals("Expected Pizza", expectedPizza, service.orderHouseSpecial());
}
}
@@ -1,32 +0,0 @@
package com.baeldung.mockito.fluentapi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.mockito.fluentapi.Pizza.PizzaSize;
public class PizzaUnitTest {
@Test
public void givenFluentPizzaApi_whenBuilt_thenPizzaHasCorrectAttributes() {
Pizza pizza = new Pizza.PizzaBuilder()
.name("Margherita")
.size(PizzaSize.LARGE)
.withExtraTopping("Mushroom")
.withStuffedCrust(false)
.willCollect(true)
.applyDiscount(20)
.build();
assertEquals("Pizza name: ", "Margherita", pizza.getName());
assertEquals("Pizza size: ", PizzaSize.LARGE, pizza.getSize());
assertEquals("Extra toppings: ", "Mushroom", pizza.getToppings()
.get(0));
assertFalse("Has stuffed crust: ", pizza.isStuffedCrust());
assertTrue("Will collect: ", pizza.isCollecting());
assertEquals("Discounts: ", Integer.valueOf(20), pizza.getDiscount());
}
}
@@ -1,39 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ArgumentMatcherWithLambdaUnitTest {
@InjectMocks
private UnemploymentServiceImpl unemploymentService;
@Mock
private JobService jobService;
@Test
public void whenPersonWithJob_thenIsNotEntitled() {
Person peter = new Person("Peter");
Person linda = new Person("Linda");
JobPosition teacher = new JobPosition("Teacher");
when(jobService.findCurrentJobPosition(
ArgumentMatchers.argThat((p) -> p.getName().equals("Peter")))
).thenReturn(Optional.of(teacher));
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda));
assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter));
}
}
@@ -1,51 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ArgumentMatcherWithoutLambdaUnitTest {
private class PeterArgumentMatcher implements ArgumentMatcher<Person> {
@Override
public boolean matches(Person p) {
return p
.getName()
.equals("Peter");
}
}
@InjectMocks
private UnemploymentServiceImpl unemploymentService;
@Mock
private JobService jobService;
@Test
public void whenPersonWithJob_thenIsNotEntitled() {
Person peter = new Person("Peter");
Person linda = new Person("Linda");
JobPosition teacher = new JobPosition("Teacher");
when(jobService.findCurrentJobPosition(
ArgumentMatchers.argThat(new PeterArgumentMatcher()))
).thenReturn(Optional.of(teacher));
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda));
assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter));
}
}
@@ -1,46 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CustomAnswerWithLambdaUnitTest {
@InjectMocks
private UnemploymentServiceImpl unemploymentService;
@Mock
private JobService jobService;
@Test
public void whenPersonWithJobHistory_thenSearchReturnsValue() {
Person peter = new Person("Peter");
assertEquals("Teacher", unemploymentService.searchJob(peter, "").get().getTitle());
}
@Test
public void whenPersonWithNoJobHistory_thenSearchReturnsEmpty() {
Person linda = new Person("Linda");
assertFalse(unemploymentService.searchJob(linda, "").isPresent());
}
@Before
public void init() {
when(jobService.listJobs(any(Person.class))).then((i) ->
Stream.of(new JobPosition("Teacher"))
.filter(p -> ((Person) i.getArgument(0)).getName().equals("Peter")));
}
}
@@ -1,60 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class CustomAnswerWithoutLambdaUnitTest {
private class PersonAnswer implements Answer<Stream<JobPosition>> {
@Override
public Stream<JobPosition> answer(InvocationOnMock invocation) throws Throwable {
Person person = invocation.getArgument(0);
if(person.getName().equals("Peter")) {
return Stream.<JobPosition>builder().add(new JobPosition("Teacher")).build();
}
return Stream.empty();
}
}
@InjectMocks
private UnemploymentServiceImpl unemploymentService;
@Mock
private JobService jobService;
@Test
public void whenPersonWithJobHistory_thenSearchReturnsValue() {
Person peter = new Person("Peter");
assertEquals("Teacher", unemploymentService.searchJob(peter, "").get().getTitle());
}
@Test
public void whenPersonWithNoJobHistory_thenSearchReturnsEmpty() {
Person linda = new Person("Linda");
assertFalse(unemploymentService.searchJob(linda, "").isPresent());
}
@Before
public void init() {
when(jobService.listJobs(any(Person.class))).then(new PersonAnswer());
}
}
@@ -1,40 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class JobServiceUnitTest {
@Mock
private JobService jobService;
@Test
public void givenDefaultMethod_whenCallRealMethod_thenNoExceptionIsRaised() {
Person person = new Person();
when(jobService.findCurrentJobPosition(person)).thenReturn(Optional.of(new JobPosition()));
doCallRealMethod().when(jobService).assignJobPosition(Mockito.any(Person.class), Mockito.any(JobPosition.class));
assertFalse(jobService.assignJobPosition(person, new JobPosition()));
}
@Test
public void givenReturnIsOfTypeOptional_whenDefaultValueIsReturned_thenValueIsEmpty() {
Person person = new Person();
when(jobService.findCurrentJobPosition(person)).thenReturn(Optional.empty());
doCallRealMethod().when(jobService).assignJobPosition(Mockito.any(Person.class), Mockito.any(JobPosition.class));
assertTrue(jobService.assignJobPosition(person, new JobPosition()));
}
}
@@ -1,58 +0,0 @@
package com.baeldung.mockito.java8;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class UnemploymentServiceImplUnitTest {
@Mock
private JobService jobService;
@InjectMocks
private UnemploymentServiceImpl unemploymentService;
@Test
public void givenReturnIsOfTypeOptional_whenMocked_thenValueIsEmpty() {
Person person = new Person();
when(jobService.findCurrentJobPosition(any(Person.class))).thenReturn(Optional.empty());
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(person));
}
@Test
public void givenReturnIsOfTypeOptional_whenDefaultValueIsReturned_thenValueIsEmpty() {
Person person = new Person();
// This will fail when Mockito 1 is used
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(person));
}
@Test
public void givenReturnIsOfTypeStream_whenMocked_thenValueIsEmpty() {
Person person = new Person();
when(jobService.listJobs(any(Person.class))).thenReturn(Stream.empty());
assertFalse(unemploymentService.searchJob(person, "").isPresent());
}
@Test
public void givenReturnIsOfTypeStream_whenDefaultValueIsReturned_thenValueIsEmpty() {
Person person = new Person();
// This will fail when Mockito 1 is used
assertFalse(unemploymentService.searchJob(person, "").isPresent());
}
}
@@ -1,34 +0,0 @@
package com.baeldung.mockito.lazyverification;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.VerificationCollector;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class LazyVerificationUnitTest {
@Test
public void whenLazilyVerified_thenReportsMultipleFailures() {
VerificationCollector collector = MockitoJUnit.collector()
.assertLazily();
List mockList = mock(List.class);
verify(mockList).add("one");
verify(mockList).clear();
try {
collector.collectAndReport();
} catch (MockitoAssertionError error) {
assertTrue(error.getMessage()
.contains("1. Wanted but not invoked:"));
assertTrue(error.getMessage()
.contains("2. Wanted but not invoked:"));
}
}
}
@@ -1,51 +0,0 @@
package com.baeldung.mockito.misusing;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class ExpectedTestFailureRule implements MethodRule {
private final MethodRule testedRule;
private FailureAssert failureAssert = null;
public ExpectedTestFailureRule(MethodRule testedRule) {
this.testedRule = testedRule;
}
@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
return new Statement() {
public void evaluate() throws Throwable {
try {
testedRule.apply(base, method, target)
.evaluate();
} catch (Throwable t) {
if (failureAssert == null) {
throw t;
}
failureAssert.doAssert(t);
return;
}
}
};
}
@SuppressWarnings("unchecked")
public void expectedFailure(final Class<? extends Throwable> expected) {
FailureAssert assertion = t -> Assert.assertThat(t, Matchers.isA((Class<Throwable>) expected));
this.expectedFailure(assertion);
}
private void expectedFailure(FailureAssert failureAssert) {
this.failureAssert = failureAssert;
}
@FunctionalInterface
private interface FailureAssert {
abstract void doAssert(Throwable t);
}
}
@@ -1,50 +0,0 @@
package com.baeldung.mockito.misusing;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.quality.Strictness;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MockitoUnecessaryStubUnitTest {
@Rule
public ExpectedTestFailureRule rule = new ExpectedTestFailureRule(MockitoJUnit.rule()
.strictness(Strictness.STRICT_STUBS));
@Mock
private ArrayList<String> mockList;
@Test
public void givenUnusedStub_whenInvokingGetThenThrowUnnecessaryStubbingException() {
rule.expectedFailure(UnnecessaryStubbingException.class);
// Commenting this stubbing so that it doesn't affect the builds.
// If you want to reproduce UnnecessaryStubbingException then uncomment below line and execute the test.
// when(mockList.add("one")).thenReturn(true);
when(mockList.get(anyInt())).thenReturn("hello");
assertEquals("List should contain hello", "hello", mockList.get(1));
}
@Test
public void givenLenientdStub_whenInvokingGetThenDontThrowUnnecessaryStubbingException() {
lenient().when(mockList.add("one"))
.thenReturn(true);
when(mockList.get(anyInt())).thenReturn("hello");
assertEquals("List should contain hello", "hello", mockList.get(1));
}
}
@@ -1,56 +0,0 @@
package com.baeldung.mockito.mocksettings;
import static org.mockito.Answers.RETURNS_SMART_NULLS;
import static org.junit.Assert.assertEquals;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.exceptions.verification.SmartNullPointerException;
import org.mockito.junit.MockitoJUnitRunner;
import com.baeldung.mockito.fluentapi.Pizza;
import com.baeldung.mockito.fluentapi.PizzaService;
@RunWith(MockitoJUnitRunner.class)
public class MockSettingsUnitTest {
@Test(expected = SmartNullPointerException.class)
public void whenServiceMockedWithSmartNulls_thenExceptionHasExtraInfo() {
PizzaService service = mock(PizzaService.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
Pizza pizza = service.orderHouseSpecial();
pizza.getSize();
}
@Test
public void whenServiceMockedWithNameAndVerboseLogging_thenLogsMethodInvocations() {
PizzaService service = mock(PizzaService.class, withSettings().name("pizzaServiceMock")
.verboseLogging());
Pizza pizza = mock(Pizza.class);
when(service.orderHouseSpecial()).thenReturn(pizza);
service.orderHouseSpecial();
verify(service).orderHouseSpecial();
}
@Test
public void whenServiceMockedWithExtraInterfaces_thenConstructorSuccess() {
SpecialInterface specialMock = mock(SpecialInterface.class, withSettings().extraInterfaces(Runnable.class));
new SimpleService(specialMock);
}
@Test
public void whenMockSetupWithConstructor_thenConstructorIsInvoked() {
AbstractCoffee coffeeSpy = mock(AbstractCoffee.class, withSettings().useConstructor("espresso")
.defaultAnswer(CALLS_REAL_METHODS));
assertEquals("Coffee name: ", "espresso", coffeeSpy.getName());
}
}
@@ -1,53 +0,0 @@
package com.baeldung.mockito.objectmapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class FlowerJsonStringValidatorUnitTest {
@Mock
private ObjectMapper objectMapper;
private FlowerJsonStringValidator flowerJsonStringValidator;
@BeforeEach
public void setUp() {
flowerJsonStringValidator = new FlowerJsonStringValidator(objectMapper);
}
@Test
public void whenCallingHasPetalsWithPetals_thenReturnsTrue() throws JsonProcessingException {
Flower rose = new Flower("testFlower", 100);
when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose);
assertTrue(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower"));
verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class));
}
@Test
public void whenCallingHasPetalsWithZeroPetal_thenReturnsFalse() throws JsonProcessingException {
Flower rose = new Flower("testFlowerWithoutPetal", 0);
when(objectMapper.readValue(anyString(), eq(Flower.class))).thenReturn(rose);
assertFalse(flowerJsonStringValidator.flowerHasPetals("this can be a very long json flower"));
verify(objectMapper, times(1)).readValue(anyString(), eq(Flower.class));
}
}
@@ -1,90 +0,0 @@
package com.baeldung.mockito.whenvsdomethods;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import java.time.DayOfWeek;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class WhenVsDoMethodsUnitTest {
@Mock
private Employee employee;
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void givenNonVoidMethod_callingWhen_shouldConfigureBehavior() {
// given
when(employee.greet()).thenReturn("Hello");
// when
String greeting = employee.greet();
// then
assertThat(greeting, is("Hello"));
}
@Test
void givenNonVoidMethod_callingDoReturn_shouldConfigureBehavior() {
// given
doReturn("Hello").when(employee).greet();
// when
String greeting = employee.greet();
// then
assertThat(greeting, is("Hello"));
}
@Test
void givenVoidMethod_callingDoThrow_shouldConfigureBehavior() {
// given
doThrow(new IAmOnHolidayException()).when(employee).work(DayOfWeek.SUNDAY);
// when
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
// then
assertThrows(IAmOnHolidayException.class, workCall);
}
@Test
void givenNonVoidMethod_callingGiven_shouldConfigureBehavior() {
// given
given(employee.greet()).willReturn("Hello");
// when
String greeting = employee.greet();
// then
assertThat(greeting, is("Hello"));
}
@Test
void givenVoidMethod_callingWillThrow_shouldConfigureBehavior() {
// given
willThrow(new IAmOnHolidayException()).given(employee).work(DayOfWeek.SUNDAY);
// when
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
// then
assertThrows(IAmOnHolidayException.class, workCall);
}
}