[BAEL-16669] moved testing-modules/testing modules into relevant folders
This commit is contained in:
@@ -1,4 +0,0 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [EasyMock Argument Matchers](http://www.baeldung.com/easymock-argument-matchers)
|
||||
- [Mock Static Method using JMockit](https://www.baeldung.com/jmockit-static-method)
|
||||
@@ -1,9 +0,0 @@
|
||||
=========
|
||||
|
||||
## JMockit related tutorials
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [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)
|
||||
@@ -1,37 +0,0 @@
|
||||
<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>jmockit</artifactId>
|
||||
<name>jmockit</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mocks</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jmockit</groupId>
|
||||
<artifactId>jmockit</artifactId>
|
||||
<version>${jmockit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jmockit</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jmockit.version>1.24</jmockit.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,26 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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{}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Collaborator {
|
||||
|
||||
public boolean collaborate(String string){
|
||||
return false;
|
||||
}
|
||||
|
||||
public void receive(boolean bool){
|
||||
//NOOP
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
public class Model {
|
||||
public String getInfo() {
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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,44 +0,0 @@
|
||||
package com.baeldung.mocks.jmockit;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import mockit.Deencapsulation;
|
||||
import mockit.Mock;
|
||||
import mockit.MockUp;
|
||||
|
||||
public class AppManagerUnitTest {
|
||||
|
||||
private AppManager appManager;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
appManager = new AppManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAppManager_whenStaticMethodCalled_thenValidateExpectedResponse() {
|
||||
new MockUp<AppManager>() {
|
||||
@Mock
|
||||
public boolean isResponsePositive(String value) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
Assertions.assertFalse(appManager.managerResponse("Why are you coming late?"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAppManager_whenPrivateStaticMethod_thenValidateExpectedResponse() {
|
||||
final int response = Deencapsulation.invoke(AppManager.class, "stringToInteger", "110");
|
||||
Assertions.assertEquals(110, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAppManager_whenPrivateStaticMethod_thenExpectException() {
|
||||
Assertions.assertThrows(IllegalArgumentException.class, () -> {
|
||||
Deencapsulation.invoke(AppManager.class, "stringToInteger", "11r");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.mocks.jmockit.AdvancedCollaborator.InnerAdvancedCollaborator;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.Deencapsulation;
|
||||
import mockit.Expectations;
|
||||
import mockit.Invocation;
|
||||
import mockit.Mock;
|
||||
import mockit.MockUp;
|
||||
import mockit.Mocked;
|
||||
import mockit.Tested;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class AdvancedCollaboratorIntegrationTest<MultiMock extends List<String> & Comparable<List<String>>> {
|
||||
|
||||
@Tested
|
||||
private AdvancedCollaborator mock;
|
||||
|
||||
@Mocked
|
||||
private MultiMock multiMock;
|
||||
|
||||
@Test
|
||||
public void testToMockUpPrivateMethod() {
|
||||
new MockUp<AdvancedCollaborator>() {
|
||||
@Mock
|
||||
private String privateMethod() {
|
||||
return "mocked: ";
|
||||
}
|
||||
};
|
||||
String res = mock.methodThatCallsPrivateMethod(1);
|
||||
assertEquals("mocked: 1", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToMockUpDifficultConstructor() throws Exception {
|
||||
new MockUp<AdvancedCollaborator>() {
|
||||
@Mock
|
||||
public void $init(Invocation invocation, String string) {
|
||||
((AdvancedCollaborator) invocation.getInvokedInstance()).i = 1;
|
||||
}
|
||||
};
|
||||
AdvancedCollaborator coll = new AdvancedCollaborator(null);
|
||||
assertEquals(1, coll.i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCallPrivateMethodsDirectly() {
|
||||
Object value = Deencapsulation.invoke(mock, "privateMethod");
|
||||
assertEquals("default:", value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToSetPrivateFieldDirectly() {
|
||||
Deencapsulation.setField(mock, "privateField", 10);
|
||||
assertEquals(10, mock.methodThatReturnsThePrivateField());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToGetPrivateFieldDirectly() {
|
||||
int value = Deencapsulation.getField(mock, "privateField");
|
||||
assertEquals(5, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCreateNewInstanceDirectly() {
|
||||
AdvancedCollaborator coll = Deencapsulation.newInstance(AdvancedCollaborator.class, "foo");
|
||||
assertEquals(3, coll.i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToCreateNewInnerClassInstanceDirectly() {
|
||||
InnerAdvancedCollaborator innerCollaborator = Deencapsulation.newInnerInstance(InnerAdvancedCollaborator.class, mock);
|
||||
assertNotNull(innerCollaborator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testMultipleInterfacesWholeTest() {
|
||||
new Expectations() {
|
||||
{
|
||||
multiMock.get(5); result = "foo";
|
||||
multiMock.compareTo((List<String>) any); result = 0;
|
||||
}
|
||||
};
|
||||
assertEquals("foo", multiMock.get(5));
|
||||
assertEquals(0, multiMock.compareTo(new ArrayList<>()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public <M extends List<String> & Comparable<List<String>>> void testMultipleInterfacesOneMethod(@Mocked M mock) {
|
||||
new Expectations() {
|
||||
{
|
||||
mock.get(5); result = "foo";
|
||||
mock.compareTo((List<String>) any);
|
||||
result = 0; }
|
||||
};
|
||||
assertEquals("foo", mock.get(5));
|
||||
assertEquals(0, mock.compareTo(new ArrayList<>()));
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import mockit.Delegate;
|
||||
import mockit.Expectations;
|
||||
import mockit.Mocked;
|
||||
import mockit.StrictExpectations;
|
||||
import mockit.Verifications;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ExpectationsIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void testForAny(@Mocked ExpectationsCollaborator mock) throws Exception {
|
||||
new Expectations() {{
|
||||
mock.methodForAny1(anyString, anyInt, anyBoolean);
|
||||
result = "any";
|
||||
}};
|
||||
|
||||
assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
|
||||
mock.methodForAny2(2L, new ArrayList<>());
|
||||
|
||||
new Verifications() {{
|
||||
mock.methodForAny2(anyLong, (List<String>) any);
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
|
||||
new Expectations() {{
|
||||
mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
|
||||
result = "with";
|
||||
}};
|
||||
|
||||
assertEquals("with", mock.methodForWith1("barfooxyz", 2));
|
||||
mock.methodForWith2(Boolean.TRUE, new ArrayList<>());
|
||||
|
||||
new Verifications() {{
|
||||
mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithNulls(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {{
|
||||
mock.methodForNulls1(anyString, null);
|
||||
result = "null";
|
||||
}};
|
||||
|
||||
assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
|
||||
mock.methodForNulls2("blablabla", null);
|
||||
|
||||
new Verifications() {{
|
||||
mock.methodForNulls2(anyString, (List<String>) withNull());
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {{
|
||||
mock.methodForTimes1();
|
||||
times = 2;
|
||||
mock.methodForTimes2();
|
||||
}};
|
||||
|
||||
mock.methodForTimes1();
|
||||
mock.methodForTimes1();
|
||||
mock.methodForTimes2();
|
||||
mock.methodForTimes3();
|
||||
mock.methodForTimes3();
|
||||
mock.methodForTimes3();
|
||||
|
||||
new Verifications() {{
|
||||
mock.methodForTimes3();
|
||||
minTimes = 1;
|
||||
maxTimes = 3;
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {{
|
||||
mock.methodForArgThat(withArgThat(new BaseMatcher<Object>() {
|
||||
@Override
|
||||
public boolean matches(Object item) {
|
||||
return item instanceof Model && "info".equals(((Model) item).getInfo());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
}
|
||||
}));
|
||||
}};
|
||||
mock.methodForArgThat(new Model());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
|
||||
new StrictExpectations() {{
|
||||
mock.methodReturnsString();
|
||||
result = "foo";
|
||||
result = new Exception();
|
||||
result = "bar";
|
||||
mock.methodReturnsInt();
|
||||
result = new int[]{1, 2, 3};
|
||||
mock.methodReturnsString();
|
||||
returns("foo", "bar");
|
||||
mock.methodReturnsInt();
|
||||
result = 1;
|
||||
}};
|
||||
|
||||
assertEquals("Should return foo", "foo", mock.methodReturnsString());
|
||||
try {
|
||||
mock.methodReturnsString();
|
||||
} catch (Exception e) {
|
||||
// NOOP
|
||||
}
|
||||
assertEquals("Should return bar", "bar", mock.methodReturnsString());
|
||||
assertEquals("Should return 1", 1, mock.methodReturnsInt());
|
||||
assertEquals("Should return 2", 2, mock.methodReturnsInt());
|
||||
assertEquals("Should return 3", 3, mock.methodReturnsInt());
|
||||
assertEquals("Should return foo", "foo", mock.methodReturnsString());
|
||||
assertEquals("Should return bar", "bar", mock.methodReturnsString());
|
||||
assertEquals("Should return 1", 1, mock.methodReturnsInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelegate(@Mocked ExpectationsCollaborator mock) {
|
||||
new Expectations() {{
|
||||
mock.methodForDelegate(anyInt);
|
||||
result = new Delegate() {
|
||||
public int delegate(int i) throws Exception {
|
||||
if (i < 3) {
|
||||
return 5;
|
||||
} else {
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
};
|
||||
}};
|
||||
|
||||
assertEquals("Should return 5", 5, mock.methodForDelegate(1));
|
||||
try {
|
||||
mock.methodForDelegate(3);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.*;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class PerformerIntegrationTest {
|
||||
|
||||
@Injectable
|
||||
private Collaborator collaborator;
|
||||
|
||||
@Tested
|
||||
private Performer performer;
|
||||
|
||||
@Test
|
||||
public void testThePerformMethod(@Mocked Model model) {
|
||||
new Expectations() {{
|
||||
model.getInfo();result = "bar";
|
||||
collaborator.collaborate("bar"); result = true;
|
||||
}};
|
||||
|
||||
performer.perform(model);
|
||||
|
||||
new Verifications() {{
|
||||
collaborator.receive(true);
|
||||
}};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import mockit.Expectations;
|
||||
import mockit.Injectable;
|
||||
import mockit.Mocked;
|
||||
import mockit.Tested;
|
||||
import mockit.Verifications;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class ReusingIntegrationTest {
|
||||
|
||||
@Injectable
|
||||
private Collaborator collaborator;
|
||||
|
||||
@Mocked
|
||||
private Model model;
|
||||
|
||||
@Tested
|
||||
private Performer performer;
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
new Expectations(){{
|
||||
model.getInfo(); result = "foo"; minTimes = 0;
|
||||
collaborator.collaborate("foo"); result = true; minTimes = 0;
|
||||
}};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSetup() {
|
||||
performer.perform(model);
|
||||
verifyTrueCalls(1);
|
||||
}
|
||||
|
||||
protected void verifyTrueCalls(int calls){
|
||||
new Verifications(){{
|
||||
collaborator.receive(true); times = calls;
|
||||
}};
|
||||
}
|
||||
|
||||
final class TrueCallsVerification extends Verifications{
|
||||
public TrueCallsVerification(int calls){
|
||||
collaborator.receive(true); times = calls;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithFinalClass() {
|
||||
performer.perform(model);
|
||||
new TrueCallsVerification(1);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
=========
|
||||
|
||||
## Mock comparison realated tutorials
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit)
|
||||
- [Introduction to EasyMock](http://www.baeldung.com/easymock)
|
||||
@@ -1,54 +0,0 @@
|
||||
<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>mock-comparisons</artifactId>
|
||||
<name>mock-comparisons</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>mocks</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<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>org.jmockit</groupId>
|
||||
<artifactId>jmockit</artifactId>
|
||||
<version>${jmockit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>mock-comparisons</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<mockito.version>2.21.0</mockito.version>
|
||||
<easymock.version>3.5.1</easymock.version>
|
||||
<jmockit.version>1.41</jmockit.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,36 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.easymock;
|
||||
|
||||
public interface IArticleWriter {
|
||||
|
||||
String write(String title, String content);
|
||||
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package org.baeldung.mocks.testCase;
|
||||
|
||||
public class LoginDao {
|
||||
|
||||
public int login(UserForm userForm) {
|
||||
//actual call to a third party library
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,220 +0,0 @@
|
||||
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("test@example.com");
|
||||
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("test@example.com");
|
||||
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("test@example.com");
|
||||
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("test@example.com");
|
||||
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("test@example.com");
|
||||
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("test@example.org");
|
||||
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("test@example.com");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.baeldung.easymock;
|
||||
|
||||
import org.junit.*;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.easymock.EasyMock.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BaeldungReaderUnitTest {
|
||||
|
||||
private BaeldungReader baeldungReader;
|
||||
|
||||
private ArticleReader mockArticleReader;
|
||||
|
||||
private IArticleWriter mockArticleWriter;
|
||||
|
||||
@Test
|
||||
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
|
||||
mockArticleReader = mock(ArticleReader.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleReader);
|
||||
|
||||
expect(mockArticleReader.next()).andReturn(null);
|
||||
replay(mockArticleReader);
|
||||
|
||||
BaeldungArticle article = baeldungReader.readNext();
|
||||
verify(mockArticleReader);
|
||||
assertEquals(null, article);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaeldungReader_whenReadNextAndSkimTopics_thenAllAllowed() {
|
||||
mockArticleReader = strictMock(ArticleReader.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleReader);
|
||||
|
||||
expect(mockArticleReader.next()).andReturn(null);
|
||||
expect(mockArticleReader.ofTopic("easymock")).andReturn(null);
|
||||
replay(mockArticleReader);
|
||||
|
||||
baeldungReader.readNext();
|
||||
baeldungReader.readTopic("easymock");
|
||||
verify(mockArticleReader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaeldungReader_whenReadNextAndOthers_thenAllowed() {
|
||||
mockArticleReader = niceMock(ArticleReader.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleReader);
|
||||
|
||||
expect(mockArticleReader.next()).andReturn(null);
|
||||
replay(mockArticleReader);
|
||||
|
||||
baeldungReader.readNext();
|
||||
baeldungReader.readTopic("easymock");
|
||||
verify(mockArticleReader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaeldungReader_whenWriteMaliciousContent_thenArgumentIllegal() {
|
||||
mockArticleWriter = mock(IArticleWriter.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleWriter);
|
||||
expect(mockArticleWriter.write("easymock", "<body onload=alert('baeldung')>")).andThrow(new IllegalArgumentException());
|
||||
replay(mockArticleWriter);
|
||||
|
||||
Exception expectedException = null;
|
||||
try {
|
||||
baeldungReader.write("easymock", "<body onload=alert('baeldung')>");
|
||||
} catch (Exception exception) {
|
||||
expectedException = exception;
|
||||
}
|
||||
|
||||
verify(mockArticleWriter);
|
||||
assertEquals(IllegalArgumentException.class, expectedException.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
|
||||
mockArticleWriter = mock(IArticleWriter.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleWriter);
|
||||
expect(mockArticleWriter.write("title", "content")).andReturn(null);
|
||||
replay(mockArticleWriter);
|
||||
String articleId = baeldungReader.write("title", "content");
|
||||
verify(mockArticleWriter);
|
||||
assertEquals(null, articleId);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
|
||||
ArticleReader mockArticleReader = mock(ArticleReader.class);
|
||||
baeldungReader = new BaeldungReader(mockArticleReader);
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package org.baeldung.mocks.easymock;
|
||||
|
||||
import org.baeldung.mocks.testCase.LoginController;
|
||||
import org.baeldung.mocks.testCase.LoginDao;
|
||||
import org.baeldung.mocks.testCase.LoginService;
|
||||
import org.baeldung.mocks.testCase.UserForm;
|
||||
import org.easymock.*;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(EasyMockRunner.class)
|
||||
public class LoginControllerIntegrationTest {
|
||||
|
||||
@Mock
|
||||
private LoginDao loginDao;
|
||||
|
||||
@Mock
|
||||
private LoginService loginService;
|
||||
|
||||
@TestSubject
|
||||
private LoginController loginController = new LoginController();
|
||||
|
||||
@Test
|
||||
public void assertThatNoMethodHasBeenCalled() {
|
||||
EasyMock.replay(loginService);
|
||||
loginController.login(null);
|
||||
|
||||
// no method called
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertTwoMethodsHaveBeenCalled() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
EasyMock.expect(loginService.login(userForm)).andReturn(true);
|
||||
loginService.setCurrentUser("foo");
|
||||
EasyMock.replay(loginService);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertOnlyOneMethodHasBeenCalled() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
EasyMock.expect(loginService.login(userForm)).andReturn(false);
|
||||
EasyMock.replay(loginService);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("KO", login);
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockExceptionThrowing() {
|
||||
UserForm userForm = new UserForm();
|
||||
EasyMock.expect(loginService.login(userForm)).andThrow(new IllegalArgumentException());
|
||||
EasyMock.replay(loginService);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("ERROR", login);
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockAnObjectToPassAround() {
|
||||
UserForm userForm = EasyMock.mock(UserForm.class);
|
||||
EasyMock.expect(userForm.getUsername()).andReturn("foo");
|
||||
EasyMock.expect(loginService.login(userForm)).andReturn(true);
|
||||
loginService.setCurrentUser("foo");
|
||||
EasyMock.replay(userForm);
|
||||
EasyMock.replay(loginService);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
EasyMock.verify(userForm);
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void argumentMatching() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// default matcher
|
||||
EasyMock.expect(loginService.login(EasyMock.isA(UserForm.class))).andReturn(true);
|
||||
// complex matcher
|
||||
loginService.setCurrentUser(specificArgumentMatching("foo"));
|
||||
EasyMock.replay(loginService);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
EasyMock.verify(loginService);
|
||||
}
|
||||
|
||||
private static String specificArgumentMatching(final String expected) {
|
||||
EasyMock.reportMatcher(new IArgumentMatcher() {
|
||||
@Override
|
||||
public boolean matches(Object argument) {
|
||||
return argument instanceof String && ((String) argument).startsWith(expected);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void appendTo(StringBuffer buffer) {
|
||||
//NOOP
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void partialMocking() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// use partial mock
|
||||
LoginService loginServicePartial = EasyMock.partialMockBuilder(LoginService.class).
|
||||
addMockedMethod("setCurrentUser").createMock();
|
||||
loginServicePartial.setCurrentUser("foo");
|
||||
// let service's login use implementation so let's mock DAO call
|
||||
EasyMock.expect(loginDao.login(userForm)).andReturn(1);
|
||||
|
||||
loginServicePartial.setLoginDao(loginDao);
|
||||
loginController.loginService = loginServicePartial;
|
||||
|
||||
EasyMock.replay(loginDao);
|
||||
EasyMock.replay(loginServicePartial);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
// verify mocked call
|
||||
EasyMock.verify(loginServicePartial);
|
||||
EasyMock.verify(loginDao);
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package org.baeldung.mocks.jmockit;
|
||||
|
||||
import mockit.*;
|
||||
import mockit.integration.junit4.JMockit;
|
||||
import org.baeldung.mocks.testCase.LoginController;
|
||||
import org.baeldung.mocks.testCase.LoginDao;
|
||||
import org.baeldung.mocks.testCase.LoginService;
|
||||
import org.baeldung.mocks.testCase.UserForm;
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(JMockit.class)
|
||||
public class LoginControllerIntegrationTest {
|
||||
|
||||
@Injectable
|
||||
private LoginDao loginDao;
|
||||
|
||||
@Injectable
|
||||
private LoginService loginService;
|
||||
|
||||
@Tested
|
||||
private LoginController loginController;
|
||||
|
||||
@Test
|
||||
public void assertThatNoMethodHasBeenCalled() {
|
||||
loginController.login(null);
|
||||
// no method called
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertTwoMethodsHaveBeenCalled() {
|
||||
final UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
new Expectations() {{
|
||||
loginService.login(userForm);
|
||||
result = true;
|
||||
loginService.setCurrentUser("foo");
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertOnlyOneMethodHasBeenCalled() {
|
||||
final UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
new Expectations() {{
|
||||
loginService.login(userForm);
|
||||
result = false;
|
||||
// no expectation for setCurrentUser
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("KO", login);
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockExceptionThrowing() {
|
||||
final UserForm userForm = new UserForm();
|
||||
new Expectations() {{
|
||||
loginService.login(userForm);
|
||||
result = new IllegalArgumentException();
|
||||
// no expectation for setCurrentUser
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("ERROR", login);
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockAnObjectToPassAround(@Mocked final UserForm userForm) {
|
||||
new Expectations() {{
|
||||
userForm.getUsername();
|
||||
result = "foo";
|
||||
loginService.login(userForm);
|
||||
result = true;
|
||||
loginService.setCurrentUser("foo");
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
new FullVerifications(userForm) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void argumentMatching() {
|
||||
final UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// default matcher
|
||||
new Expectations() {{
|
||||
loginService.login((UserForm) any);
|
||||
result = true;
|
||||
// complex matcher
|
||||
loginService.setCurrentUser(withArgThat(new BaseMatcher<String>() {
|
||||
@Override
|
||||
public boolean matches(Object item) {
|
||||
return item instanceof String && ((String) item).startsWith("foo");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
//NOOP
|
||||
}
|
||||
}));
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
new FullVerifications(loginService) {
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void partialMocking() {
|
||||
// use partial mock
|
||||
final LoginService partialLoginService = new LoginService();
|
||||
partialLoginService.setLoginDao(loginDao);
|
||||
loginController.loginService = partialLoginService;
|
||||
|
||||
final UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// let service's login use implementation so let's mock DAO call
|
||||
new Expectations() {{
|
||||
loginDao.login(userForm);
|
||||
result = 1;
|
||||
// no expectation for loginService.login
|
||||
partialLoginService.setCurrentUser("foo");
|
||||
}};
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
// verify mocked call
|
||||
new FullVerifications(partialLoginService) {
|
||||
};
|
||||
new FullVerifications(loginDao) {
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package org.baeldung.mocks.mockito;
|
||||
|
||||
import org.baeldung.mocks.testCase.LoginController;
|
||||
import org.baeldung.mocks.testCase.LoginDao;
|
||||
import org.baeldung.mocks.testCase.LoginService;
|
||||
import org.baeldung.mocks.testCase.UserForm;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.Spy;
|
||||
|
||||
public class LoginControllerIntegrationTest {
|
||||
|
||||
@Mock
|
||||
private LoginDao loginDao;
|
||||
|
||||
@Spy
|
||||
@InjectMocks
|
||||
private LoginService spiedLoginService;
|
||||
|
||||
@Mock
|
||||
private LoginService loginService;
|
||||
|
||||
@InjectMocks
|
||||
private LoginController loginController;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
loginController = new LoginController();
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertThatNoMethodHasBeenCalled() {
|
||||
loginController.login(null);
|
||||
// no method called
|
||||
Mockito.verifyZeroInteractions(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertTwoMethodsHaveBeenCalled() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
Mockito.when(loginService.login(userForm))
|
||||
.thenReturn(true);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
Mockito.verify(loginService)
|
||||
.login(userForm);
|
||||
Mockito.verify(loginService)
|
||||
.setCurrentUser("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertOnlyOneMethodHasBeenCalled() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
Mockito.when(loginService.login(userForm))
|
||||
.thenReturn(false);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("KO", login);
|
||||
Mockito.verify(loginService)
|
||||
.login(userForm);
|
||||
Mockito.verifyNoMoreInteractions(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockExceptionThrowing() {
|
||||
UserForm userForm = new UserForm();
|
||||
Mockito.when(loginService.login(userForm))
|
||||
.thenThrow(IllegalArgumentException.class);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("ERROR", login);
|
||||
Mockito.verify(loginService)
|
||||
.login(userForm);
|
||||
Mockito.verifyZeroInteractions(loginService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockAnObjectToPassAround() {
|
||||
UserForm userForm = Mockito.when(Mockito.mock(UserForm.class)
|
||||
.getUsername())
|
||||
.thenReturn("foo")
|
||||
.getMock();
|
||||
Mockito.when(loginService.login(userForm))
|
||||
.thenReturn(true);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
Mockito.verify(loginService)
|
||||
.login(userForm);
|
||||
Mockito.verify(loginService)
|
||||
.setCurrentUser("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void argumentMatching() {
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// default matcher
|
||||
Mockito.when(loginService.login(Mockito.any(UserForm.class)))
|
||||
.thenReturn(true);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
Mockito.verify(loginService)
|
||||
.login(userForm);
|
||||
// complex matcher
|
||||
Mockito.verify(loginService)
|
||||
.setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher<String>() {
|
||||
@Override
|
||||
public boolean matches(String argument) {
|
||||
return argument.startsWith("foo");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void partialMocking() {
|
||||
// use partial mock
|
||||
loginController.loginService = spiedLoginService;
|
||||
UserForm userForm = new UserForm();
|
||||
userForm.username = "foo";
|
||||
// let service's login use implementation so let's mock DAO call
|
||||
Mockito.when(loginDao.login(userForm))
|
||||
.thenReturn(1);
|
||||
|
||||
String login = loginController.login(userForm);
|
||||
|
||||
Assert.assertEquals("OK", login);
|
||||
// verify mocked call
|
||||
Mockito.verify(spiedLoginService)
|
||||
.setCurrentUser("foo");
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<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>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>mock-comparisons</module>
|
||||
<module>jmockit</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
Reference in New Issue
Block a user