BAEL-19988: Migrate mocks module to the com.baeldung package

This commit is contained in:
Krzysztof Woyke
2019-12-19 11:17:45 +01:00
parent f84ff448c5
commit aca11c38f9
18 changed files with 39 additions and 31 deletions
@@ -0,0 +1,143 @@
package com.baeldung.easymock;
import com.baeldung.testCase.LoginController;
import com.baeldung.testCase.LoginDao;
import com.baeldung.testCase.LoginService;
import com.baeldung.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);
}
}
@@ -0,0 +1,91 @@
package com.baeldung.jmockit;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jmockit.AdvancedCollaborator;
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 testToSetPrivateFieldDirectly() {
Deencapsulation.setField(mock, "privateField", 10);
assertEquals(10, mock.methodThatReturnsThePrivateField());
}
@Test
public void testToGetPrivateFieldDirectly() {
int value = Deencapsulation.getField(mock, "privateField");
assertEquals(5, value);
}
@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,10 +1,9 @@
package com.baeldung.mocks.jmockit;
package com.baeldung.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;
@@ -0,0 +1,159 @@
package com.baeldung.jmockit;
import com.baeldung.jmockit.ExpectationsCollaborator;
import com.baeldung.jmockit.Model;
import mockit.Delegate;
import mockit.Expectations;
import mockit.Mocked;
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 Expectations() {{
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) {
}
}
}
@@ -0,0 +1,159 @@
package com.baeldung.jmockit;
import mockit.*;
import mockit.integration.junit4.JMockit;
import com.baeldung.testCase.LoginController;
import com.baeldung.testCase.LoginDao;
import com.baeldung.testCase.LoginService;
import com.baeldung.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) {
};
}
}
@@ -0,0 +1,35 @@
package com.baeldung.jmockit;
import com.baeldung.jmockit.Collaborator;
import com.baeldung.jmockit.Model;
import com.baeldung.jmockit.Performer;
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);
}};
}
}
@@ -0,0 +1,60 @@
package com.baeldung.jmockit;
import com.baeldung.jmockit.Collaborator;
import com.baeldung.jmockit.Model;
import com.baeldung.jmockit.Performer;
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);
}
}
@@ -0,0 +1,149 @@
package com.baeldung.mockito;
import com.baeldung.testCase.LoginController;
import com.baeldung.testCase.LoginDao;
import com.baeldung.testCase.LoginService;
import com.baeldung.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");
}
}