Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
## Relevant articles:
- [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers)
- [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method)
- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit)
- [Introduction to EasyMock](http://www.baeldung.com/easymock)
- [JMockit 101](http://www.baeldung.com/jmockit-101)
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)
- [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage)
- [Introduction to Jukito](http://www.baeldung.com/jukito)
- [A Guide to JavaFaker](https://www.baeldung.com/java-faker)
- [File System Mocking with Jimfs](https://www.baeldung.com/jimfs-file-system-mocking)
+62
View File
@@ -0,0 +1,62 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mocks</artifactId>
<name>mocks</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>${javafaker.version}</version>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jukito</groupId>
<artifactId>jukito</artifactId>
<version>${jukito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.jimfs</groupId>
<artifactId>jimfs</artifactId>
<version>${jimf.version}</version>
</dependency>
</dependencies>
<properties>
<javafaker.version>0.15</javafaker.version>
<jukito.version>1.5</jukito.version>
<mockito.version>2.21.0</mockito.version>
<easymock.version>3.5.1</easymock.version>
<jmockit.version>1.41</jmockit.version>
<jimf.version>1.1</jimf.version>
</properties>
</project>
@@ -0,0 +1,36 @@
package com.baeldung.easymock;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class ArticleReader {
private List<BaeldungArticle> articles;
private Iterator<BaeldungArticle> articleIter;
public ArticleReader() {
this(new ArrayList<>());
}
public ArticleReader(List<BaeldungArticle> articles) {
this.articles = articles;
this.articleIter = this.articles.iterator();
}
public List<BaeldungArticle> ofTopic(String topic) {
return articles
.stream()
.filter(article -> article
.title()
.contains(topic))
.collect(toList());
}
public BaeldungArticle next() {
return this.articleIter.next();
}
}
@@ -0,0 +1,25 @@
package com.baeldung.easymock;
public class BaeldungArticle {
public static BaeldungArticle simpleArticle(String title, String content) {
return new BaeldungArticle(title, content);
}
private String title;
private String content;
private BaeldungArticle(String title, String content) {
this.title = title;
this.content = content;
}
public String title() {
return this.title;
}
public String content() {
return this.content;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.easymock;
import java.util.List;
public class BaeldungReader {
private ArticleReader articleReader;
private IArticleWriter articleWriter;
public BaeldungReader() {
}
;
public BaeldungReader(ArticleReader articleReader) {
this.articleReader = articleReader;
}
public BaeldungReader(IArticleWriter writer) {
this.articleWriter = writer;
}
public BaeldungReader(ArticleReader articleReader, IArticleWriter writer) {
this.articleReader = articleReader;
this.articleWriter = writer;
}
public BaeldungArticle readNext() {
return articleReader.next();
}
public List<BaeldungArticle> readTopic(String topic) {
return articleReader.ofTopic(topic);
}
public String write(String title, String content) {
return articleWriter.write(title, content);
}
}
@@ -0,0 +1,7 @@
package com.baeldung.easymock;
public interface IArticleWriter {
String write(String title, String content);
}
@@ -0,0 +1,9 @@
package com.baeldung.easymock;
import java.util.List;
public interface IUserService {
public boolean addUser(User user);
public List<User> findByEmail(String email);
public List<User> findByAge(double age);
}
@@ -0,0 +1,109 @@
package com.baeldung.easymock;
public class User {
private long id;
private String firstName;
private String lastName;
private double age;
private String email;
public User() {
super();
}
public User(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
//
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(age);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
User other = (User) obj;
if (Double.doubleToLongBits(age) != Double.doubleToLongBits(other.age)) {
return false;
}
if (email == null) {
if (other.email != null) {
return false;
}
} else if (!email.equals(other.email)) {
return false;
}
if (firstName == null) {
if (other.firstName != null) {
return false;
}
} else if (!firstName.equals(other.firstName)) {
return false;
}
if (id != other.id) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
} else if (!lastName.equals(other.lastName)) {
return false;
}
return true;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.introductionjukito;
public interface Calculator {
public double add(double a, double b);
}
@@ -0,0 +1,5 @@
package com.baeldung.introductionjukito;
public class ScientificCalculator extends SimpleCalculator {
}
@@ -0,0 +1,10 @@
package com.baeldung.introductionjukito;
public class SimpleCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a+b;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jimfs;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileManipulation {
void move(final Path origin, final Path destination) {
try {
Files.createDirectories(destination);
Files.move(origin, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jimfs;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
class FilePathReader {
String getSystemPath(final Path path) {
try {
return path
.toRealPath()
.toString();
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
@@ -0,0 +1,43 @@
package com.baeldung.jimfs;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileRepository {
void create(final Path path, final String fileName) {
final Path filePath = path.resolve(fileName);
try {
Files.createFile(filePath);
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
String read(final Path path) {
try {
return new String(Files.readAllBytes(path));
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
String update(final Path path, final String newContent) {
try {
Files.write(path, newContent.getBytes());
return newContent;
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
void delete(final Path path) {
try {
Files.deleteIfExists(path);
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.mocks.jmockit;
import java.util.Random;
public class AppManager {
public boolean managerResponse(String question) {
return AppManager.isResponsePositive(question);
}
public static boolean isResponsePositive(String value) {
if (value == null)
return false;
int orgLength = value.length();
int randomNumber = randomNumber();
return orgLength == randomNumber ? true : false;
}
private static int randomNumber() {
return new Random().nextInt(7);
}
private static Integer stringToInteger(String num) {
return Integer.parseInt(num);
}
}
@@ -0,0 +1,20 @@
package org.baeldung.mocks.jmockit;
public class AdvancedCollaborator {
int i;
private int privateField = 5;
public AdvancedCollaborator(){}
public AdvancedCollaborator(String string) throws Exception{
i = string.length();
}
public String methodThatCallsPrivateMethod(int i){
return privateMethod() + i;
}
public int methodThatReturnsThePrivateField(){
return privateField;
}
private String privateMethod(){
return "default:";
}
class InnerAdvancedCollaborator{}
}
@@ -0,0 +1,12 @@
package org.baeldung.mocks.jmockit;
public class Collaborator {
public boolean collaborate(String string){
return false;
}
public void receive(boolean bool){
//NOOP
}
}
@@ -0,0 +1,19 @@
package org.baeldung.mocks.jmockit;
import java.util.List;
public interface ExpectationsCollaborator {
String methodForAny1(String s, int i, Boolean b);
void methodForAny2(Long l, List<String> lst);
String methodForWith1(String s, int i);
void methodForWith2(Boolean b, List<String> l);
String methodForNulls1(String s, List<String> l);
void methodForNulls2(String s, List<String> l);
void methodForTimes1();
void methodForTimes2();
void methodForTimes3();
void methodForArgThat(Object o);
String methodReturnsString();
int methodReturnsInt();
Object methodForDelegate(int i);
}
@@ -0,0 +1,7 @@
package org.baeldung.mocks.jmockit;
public class Model {
public String getInfo() {
return "info";
}
}
@@ -0,0 +1,10 @@
package org.baeldung.mocks.jmockit;
public class Performer {
private Collaborator collaborator;
public void perform(Model model){
boolean value = collaborator.collaborate(model.getInfo());
collaborator.receive(value);
}
}
@@ -0,0 +1,29 @@
package org.baeldung.mocks.testCase;
public class LoginController {
public LoginService loginService;
public String login(UserForm userForm) {
if (null == userForm) {
return "ERROR";
} else {
boolean logged;
try {
logged = loginService.login(userForm);
} catch (Exception e) {
return "ERROR";
}
if (logged) {
loginService.setCurrentUser(userForm.getUsername());
return "OK";
} else {
return "KO";
}
}
}
// standard setters and getters
}
@@ -0,0 +1,9 @@
package org.baeldung.mocks.testCase;
public class LoginDao {
public int login(UserForm userForm) {
//actual call to a third party library
return 0;
}
}
@@ -0,0 +1,33 @@
package org.baeldung.mocks.testCase;
public class LoginService {
private LoginDao loginDao;
private String currentUser;
public boolean login(UserForm userForm) {
assert null != userForm;
int loginResults = loginDao.login(userForm);
switch (loginResults) {
case 1:
return true;
default:
return false;
}
}
public void setCurrentUser(String username) {
if (null != username) {
this.currentUser = username;
}
}
public void setLoginDao(LoginDao loginDao) {
this.loginDao = loginDao;
}
// standard setters and getters
}
@@ -0,0 +1,15 @@
package org.baeldung.mocks.testCase;
public class UserForm {
// public access modifiers as only for testing
public String password;
public String username;
public String getUsername() {
return username;
}
}
@@ -0,0 +1,13 @@
<?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>
@@ -0,0 +1,220 @@
package com.baeldung.easymock;
import static org.easymock.EasyMock.and;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.contains;
import static org.easymock.EasyMock.endsWith;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.geq;
import static org.easymock.EasyMock.gt;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.isNull;
import static org.easymock.EasyMock.lt;
import static org.easymock.EasyMock.matches;
import static org.easymock.EasyMock.mock;
import static org.easymock.EasyMock.not;
import static org.easymock.EasyMock.notNull;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.same;
import static org.easymock.EasyMock.startsWith;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import java.util.List;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import org.junit.Test;
public class ArgumentMatchersUnitTest {
private IUserService userService = mock(IUserService.class);
//====================== equals
@Test
public void givenUserService_whenAddNewUser_thenOK() {
expect(userService.addUser(eq(new User()))).andReturn(true);
replay(userService);
boolean result = userService.addUser(new User());
verify(userService);
assertTrue(result);
}
//================ same
@Test
public void givenUserService_whenAddSpecificUser_thenOK() {
User user = new User();
expect(userService.addUser(same(user))).andReturn(true);
replay(userService);
boolean result = userService.addUser(user);
verify(userService);
assertTrue(result);
}
//============= anyX
@Test
public void givenUserService_whenSearchForUserByEmail_thenFound() {
expect(userService.findByEmail(anyString())).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//================= isA
@Test
public void givenUserService_whenAddUser_thenOK() {
expect(userService.addUser(isA(User.class))).andReturn(true);
replay(userService);
boolean result = userService.addUser(new User());
verify(userService);
assertTrue(result);
}
//=================== null, not null
@Test
public void givenUserService_whenAddNull_thenFail() {
expect(userService.addUser(isNull())).andReturn(false);
replay(userService);
boolean result = userService.addUser(null);
verify(userService);
assertFalse(result);
}
@Test
public void givenUserService_whenAddNotNull_thenOK() {
expect(userService.addUser(notNull())).andReturn(true);
replay(userService);
boolean result = userService.addUser(new User());
verify(userService);
assertTrue(result);
}
// number less,great
@Test
public void givenUserService_whenSearchForUserByAgeLessThan_thenFound() {
expect(userService.findByAge(lt(100.0))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByAge(20);
verify(userService);
assertEquals(0,result.size());
}
@Test
public void givenUserService_whenSearchForUserByAgeGreaterThan_thenFound() {
expect(userService.findByAge(geq(10.0))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByAge(20);
verify(userService);
assertEquals(0,result.size());
}
//=============== string
//=============== start
@Test
public void givenUserService_whenSearchForUserByEmailStartsWith_thenFound() {
expect(userService.findByEmail(startsWith("test"))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//==================end
@Test
public void givenUserService_whenSearchForUserByEmailEndsWith_thenFound() {
expect(userService.findByEmail(endsWith(".com"))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//=================contain
@Test
public void givenUserService_whenSearchForUserByEmailContains_thenFound() {
expect(userService.findByEmail(contains("@"))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//==================matches
@Test
public void givenUserService_whenSearchForUserByEmailMatches_thenFound() {
expect(userService.findByEmail(matches(".+\\@.+\\..+"))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//================== combine and, or, not
@Test
public void givenUserService_whenSearchForUserByAgeRange_thenFound() {
expect(userService.findByAge(and(gt(10.0),lt(100.0)))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByAge(20);
verify(userService);
assertEquals(0,result.size());
}
@Test
public void givenUserService_whenSearchForUserByEmailNotEndsWith_thenFound() {
expect(userService.findByEmail(not(endsWith(".com")))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
//================ custom matcher
@Test
public void givenUserService_whenSearchForUserByEmailCharCount_thenFound() {
expect(userService.findByEmail(minCharCount(5))).andReturn(Collections.emptyList());
replay(userService);
List<User> result = userService.findByEmail("[email protected]");
verify(userService);
assertEquals(0,result.size());
}
public static String minCharCount(int value){
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object argument) {
return argument instanceof String
&& ((String) argument).length() >= value;
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("charCount(\"" + value + "\")");
}
});
return null;
}
}
@@ -0,0 +1,57 @@
package com.baeldung.easymock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderAnnotatedUnitTest {
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}
@@ -0,0 +1,57 @@
package com.baeldung.easymock;
import org.easymock.EasyMockRule;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
public class BaeldungReaderAnnotatedWithRuleUnitTest {
@Rule public EasyMockRule mockRule = new EasyMockRule(this);
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import static org.easymock.EasyMock.*;
public class BaeldungReaderMockDelegationUnitTest {
EasyMockSupport easyMockSupport = new EasyMockSupport();
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
ArticleReader mockArticleReader = easyMockSupport.createMock(ArticleReader.class);
IArticleWriter mockArticleWriter = easyMockSupport.createMock(IArticleWriter.class);
BaeldungReader baeldungReader = new BaeldungReader(mockArticleReader, mockArticleWriter);
expect(mockArticleReader.next()).andReturn(null);
expect(mockArticleWriter.write("title", "content")).andReturn("");
easyMockSupport.replayAll();
baeldungReader.readNext();
baeldungReader.write("title", "content");
easyMockSupport.verifyAll();
}
}
@@ -0,0 +1,42 @@
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderMockSupportUnitTest extends EasyMockSupport {
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
expect(mockArticleWriter.write("title", "content")).andReturn("BAEL-201801");
replayAll();
Exception expectedException = null;
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception exception) {
expectedException = exception;
}
String articleId = baeldungReader.write("title", "content");
verifyAll();
assertEquals(NoSuchElementException.class, expectedException.getClass());
assertEquals("BAEL-201801", articleId);
}
}

Some files were not shown because too many files have changed in this diff Show More