提交 d66c733e 编写于 作者: P Phillip Webb 提交者: Chris Beams

Replace EasyMock with Mockito in test sources

Issue: SPR-10126
上级 cbf6991d
......@@ -74,7 +74,7 @@ configure(allprojects) {
dependencies {
testCompile("junit:junit:${junitVersion}")
testCompile("org.hamcrest:hamcrest-all:1.3")
testCompile("org.easymock:easymock:${easymockVersion}")
testCompile("org.mockito:mockito-core:1.9.5")
}
ext.javadocLinks = [
......@@ -100,6 +100,16 @@ configure(allprojects) {
] as String[]
}
configure(allprojects.findAll{it.name in ["spring", "spring-jms", "spring-orm",
"spring-orm-hibernate4", "spring-oxm", "spring-struts", "spring-test",
"spring-test-mvc", "spring-tx", "spring-web", "spring-webmvc",
"spring-webmvc-portlet", "spring-webmvc-tiles3"]}) {
dependencies {
testCompile("org.easymock:easymock:${easymockVersion}")
testCompile "org.easymock:easymockclassextension:${easymockVersion}"
}
}
configure(subprojects) { subproject ->
apply plugin: "merge"
apply from: "${gradleScriptDir}/publish-maven.gradle"
......@@ -330,7 +340,6 @@ project("spring-tx") {
optional("javax.resource:connector-api:1.5")
optional("org.apache.geronimo.specs:geronimo-jta_1.1_spec:1.1")
optional("javax.ejb:ejb-api:3.0")
testCompile "org.easymock:easymockclassextension:${easymockVersion}"
testCompile("javax.persistence:persistence-api:1.0")
testCompile("org.aspectj:aspectjweaver:${aspectjVersion}")
}
......@@ -678,7 +687,6 @@ project("spring-test-mvc") {
testCompile("javax.activation:activation:1.1")
testCompile("javax.mail:mail:1.4")
testCompile("javax.xml.bind:jaxb-api:2.2.6")
testCompile("org.easymock:easymockclassextension:${easymockVersion}")
testCompile("org.apache.tiles:tiles-request-api:1.0.1")
testCompile("org.apache.tiles:tiles-api:3.0.1")
testCompile("org.apache.tiles:tiles-core:3.0.1") {
......
......@@ -23,8 +23,10 @@ import java.rmi.RemoteException;
import javax.transaction.TransactionRolledbackException;
import org.aopalliance.intercept.MethodInvocation;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import test.aop.MethodCounter;
......@@ -47,12 +49,10 @@ public final class ThrowsAdviceInterceptorTests {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
Object ret = new Object();
MethodInvocation mi = createMock(MethodInvocation.class);
expect(mi.proceed()).andReturn(ret);
replay(mi);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willReturn(ret);
assertEquals(ret, ti.invoke(mi));
assertEquals(0, th.getCalls());
verify(mi);
}
@Test
......@@ -61,9 +61,8 @@ public final class ThrowsAdviceInterceptorTests {
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
assertEquals(2, ti.getHandlerMethodCount());
Exception ex = new Exception();
MethodInvocation mi = createMock(MethodInvocation.class);
expect(mi.proceed()).andThrow(ex);
replay(mi);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
......@@ -72,7 +71,6 @@ public final class ThrowsAdviceInterceptorTests {
assertEquals(ex, caught);
}
assertEquals(0, th.getCalls());
verify(mi);
}
@Test
......@@ -80,12 +78,10 @@ public final class ThrowsAdviceInterceptorTests {
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
FileNotFoundException ex = new FileNotFoundException();
MethodInvocation mi = createMock(MethodInvocation.class);
expect(mi.getMethod()).andReturn(Object.class.getMethod("hashCode", (Class[]) null));
expect(mi.getArguments()).andReturn(null);
expect(mi.getThis()).andReturn(new Object());
expect(mi.proceed()).andThrow(ex);
replay(mi);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.getMethod()).willReturn(Object.class.getMethod("hashCode", (Class[]) null));
given(mi.getThis()).willReturn(new Object());
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
......@@ -95,7 +91,6 @@ public final class ThrowsAdviceInterceptorTests {
}
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("ioException"));
verify(mi);
}
@Test
......@@ -104,9 +99,8 @@ public final class ThrowsAdviceInterceptorTests {
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
// Extends RemoteException
TransactionRolledbackException ex = new TransactionRolledbackException();
MethodInvocation mi = createMock(MethodInvocation.class);
expect(mi.proceed()).andThrow(ex);
replay(mi);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
......@@ -116,7 +110,6 @@ public final class ThrowsAdviceInterceptorTests {
}
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("remoteException"));
verify(mi);
}
@Test
......@@ -135,9 +128,8 @@ public final class ThrowsAdviceInterceptorTests {
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
// Extends RemoteException
TransactionRolledbackException ex = new TransactionRolledbackException();
MethodInvocation mi = createMock(MethodInvocation.class);
expect(mi.proceed()).andThrow(ex);
replay(mi);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
try {
ti.invoke(mi);
fail();
......@@ -147,7 +139,6 @@ public final class ThrowsAdviceInterceptorTests {
}
assertEquals(1, th.getCalls());
assertEquals(1, th.getCalls("remoteException"));
verify(mi);
}
@SuppressWarnings("serial")
......
......@@ -16,8 +16,13 @@
package org.springframework.aop.interceptor;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.lang.reflect.Method;
......@@ -83,47 +88,32 @@ public final class CustomizableTraceInterceptorTests {
@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
MethodInvocation methodInvocation = mock(MethodInvocation.class);
given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[]{}));
given(methodInvocation.getThis()).willReturn(this);
Method toString = String.class.getMethod("toString", new Class[]{});
expect(log.isTraceEnabled()).andReturn(true);
expect(methodInvocation.getMethod()).andReturn(toString).times(4);
expect(methodInvocation.getThis()).andReturn(this).times(2);
log.trace(isA(String.class));
expect(methodInvocation.proceed()).andReturn(null);
log.trace(isA(String.class));
replay(methodInvocation);
replay(log);
Log log = mock(Log.class);
given(log.isTraceEnabled()).willReturn(true);
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
interceptor.invoke(methodInvocation);
verify(log);
verify(methodInvocation);
verify(log, times(2)).trace(anyString());
}
@Test
public void testExceptionPathLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
MethodInvocation methodInvocation = mock(MethodInvocation.class);
Method toString = String.class.getMethod("toString", new Class[]{});
expect(log.isTraceEnabled()).andReturn(true);
expect(methodInvocation.getMethod()).andReturn(toString).times(4);
expect(methodInvocation.getThis()).andReturn(this).times(2);
log.trace(isA(String.class));
IllegalArgumentException exception = new IllegalArgumentException();
expect(methodInvocation.proceed()).andThrow(exception);
log.trace(isA(String.class), eq(exception));
given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[]{}));
given(methodInvocation.getThis()).willReturn(this);
given(methodInvocation.proceed()).willThrow(exception);
replay(log);
replay(methodInvocation);
Log log = mock(Log.class);
given(log.isTraceEnabled()).willReturn(true);
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
try {
......@@ -133,29 +123,22 @@ public final class CustomizableTraceInterceptorTests {
catch (IllegalArgumentException expected) {
}
verify(log);
verify(methodInvocation);
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));
}
@Test
public void testSunnyDayPathLogsCorrectlyWithPrettyMuchAllPlaceholdersMatching() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
Method toString = String.class.getMethod("toString", new Class[0]);
Object[] arguments = new Object[]{"$ One \\$", new Long(2)};
MethodInvocation methodInvocation = mock(MethodInvocation.class);
expect(log.isTraceEnabled()).andReturn(true);
expect(methodInvocation.getMethod()).andReturn(toString).times(7);
expect(methodInvocation.getThis()).andReturn(this).times(2);
expect(methodInvocation.getArguments()).andReturn(arguments).times(2);
log.trace(isA(String.class));
expect(methodInvocation.proceed()).andReturn("Hello!");
log.trace(isA(String.class));
given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
given(methodInvocation.getThis()).willReturn(this);
given(methodInvocation.getArguments()).willReturn(new Object[]{"$ One \\$", new Long(2)});
given(methodInvocation.proceed()).willReturn("Hello!");
replay(methodInvocation);
replay(log);
Log log = mock(Log.class);
given(log.isTraceEnabled()).willReturn(true);
CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
interceptor.setEnterMessage(new StringBuffer()
......@@ -174,8 +157,7 @@ public final class CustomizableTraceInterceptorTests {
.append("' this long.").toString());
interceptor.invoke(methodInvocation);
verify(log);
verify(methodInvocation);
verify(log, times(2)).trace(anyString());
}
......
......@@ -16,8 +16,13 @@
package org.springframework.aop.interceptor;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
......@@ -33,40 +38,29 @@ public final class DebugInterceptorTests {
@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
MethodInvocation methodInvocation = mock(MethodInvocation.class);
expect(log.isTraceEnabled()).andReturn(true);
log.trace(isA(String.class));
expect(methodInvocation.proceed()).andReturn(null);
log.trace(isA(String.class));
replay(methodInvocation);
replay(log);
Log log = mock(Log.class);
given(log.isTraceEnabled()).willReturn(true);
DebugInterceptor interceptor = new StubDebugInterceptor(log);
interceptor.invoke(methodInvocation);
checkCallCountTotal(interceptor);
verify(methodInvocation);
verify(log);
verify(log, times(2)).trace(anyString());
}
@Test
public void testExceptionPathStillLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
MethodInvocation methodInvocation = mock(MethodInvocation.class);
expect(log.isTraceEnabled()).andReturn(true);
log.trace(isA(String.class));
IllegalArgumentException exception = new IllegalArgumentException();
expect(methodInvocation.proceed()).andThrow(exception);
log.trace(isA(String.class), eq(exception));
given(methodInvocation.proceed()).willThrow(exception);
replay(methodInvocation);
replay(log);
Log log = mock(Log.class);
given(log.isTraceEnabled()).willReturn(true);
DebugInterceptor interceptor = new StubDebugInterceptor(log);
try {
......@@ -76,8 +70,8 @@ public final class DebugInterceptorTests {
}
checkCallCountTotal(interceptor);
verify(methodInvocation);
verify(log);
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));
}
private void checkCallCountTotal(DebugInterceptor interceptor) {
......
......@@ -16,10 +16,11 @@
package org.springframework.aop.interceptor;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
......@@ -48,35 +49,24 @@ public final class PerformanceMonitorInterceptorTests {
@Test
public void testSunnyDayPathLogsPerformanceMetricsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation mi = createMock(MethodInvocation.class);
Method toString = String.class.getMethod("toString", new Class[0]);
expect(mi.getMethod()).andReturn(toString);
expect(mi.proceed()).andReturn(null);
log.trace(isA(String.class));
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
replay(mi, log);
Log log = mock(Log.class);
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
interceptor.invokeUnderTrace(mi, log);
verify(mi, log);
verify(log).trace(anyString());
}
@Test
public void testExceptionPathStillLogsPerformanceMetricsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation mi = createMock(MethodInvocation.class);
Method toString = String.class.getMethod("toString", new Class[0]);
expect(mi.getMethod()).andReturn(toString);
expect(mi.proceed()).andThrow(new IllegalArgumentException());
log.trace(isA(String.class));
MethodInvocation mi = mock(MethodInvocation.class);
replay(mi, log);
given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
given(mi.proceed()).willThrow(new IllegalArgumentException());
Log log = mock(Log.class);
PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(true);
try {
......@@ -86,7 +76,7 @@ public final class PerformanceMonitorInterceptorTests {
catch (IllegalArgumentException expected) {
}
verify(mi, log);
verify(log).trace(anyString());
}
}
......@@ -16,8 +16,13 @@
package org.springframework.aop.interceptor;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.lang.reflect.Method;
......@@ -35,39 +40,27 @@ public final class SimpleTraceInterceptorTests {
@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation mi = createMock(MethodInvocation.class);
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[]{}));
given(mi.getThis()).willReturn(this);
Method toString = String.class.getMethod("toString", new Class[]{});
expect(mi.getMethod()).andReturn(toString);
expect(mi.getThis()).andReturn(this);
log.trace(isA(String.class));
expect(mi.proceed()).andReturn(null);
log.trace(isA(String.class));
replay(mi, log);
Log log = mock(Log.class);
SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
interceptor.invokeUnderTrace(mi, log);
verify(mi, log);
verify(log, times(2)).trace(anyString());
}
@Test
public void testExceptionPathStillLogsCorrectly() throws Throwable {
Log log = createMock(Log.class);
MethodInvocation mi = createMock(MethodInvocation.class);
Method toString = String.class.getMethod("toString", new Class[]{});
expect(mi.getMethod()).andReturn(toString);
expect(mi.getThis()).andReturn(this);
log.trace(isA(String.class));
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[]{}));
given(mi.getThis()).willReturn(this);
IllegalArgumentException exception = new IllegalArgumentException();
expect(mi.proceed()).andThrow(exception);
log.trace(isA(String.class));
given(mi.proceed()).willThrow(exception);
replay(mi, log);
Log log = mock(Log.class);
final SimpleTraceInterceptor interceptor = new SimpleTraceInterceptor(true);
......@@ -77,7 +70,8 @@ public final class SimpleTraceInterceptorTests {
} catch (IllegalArgumentException expected) {
}
verify(mi, log);
verify(log).trace(anyString());
verify(log).trace(anyString(), eq(exception));
}
}
......@@ -16,7 +16,7 @@
package org.springframework.aop.scope;
import static org.easymock.EasyMock.*;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
......@@ -52,14 +52,9 @@ public final class DefaultScopedObjectTests {
testBadTargetBeanName(" ");
}
private static void testBadTargetBeanName(final String badTargetBeanName) {
ConfigurableBeanFactory factory = createMock(ConfigurableBeanFactory.class);
replay(factory);
ConfigurableBeanFactory factory = mock(ConfigurableBeanFactory.class);
new DefaultScopedObject(factory, badTargetBeanName);
verify(factory);
}
}
......@@ -16,8 +16,9 @@
package org.springframework.aop.support;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.io.Serializable;
......@@ -56,17 +57,14 @@ public final class DelegatingIntroductionInterceptorTests {
assertTrue(! (raw instanceof TimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = createMock(TimeStamped.class);
TimeStamped ts = mock(TimeStamped.class);
long timestamp = 111L;
expect(ts.getTimeStamp()).andReturn(timestamp);
replay(ts);
given(ts.getTimeStamp()).willReturn(timestamp);
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts)));
TimeStamped tsp = (TimeStamped) factory.getProxy();
assertTrue(tsp.getTimeStamp() == timestamp);
verify(ts);
}
@Test
......@@ -75,17 +73,14 @@ public final class DelegatingIntroductionInterceptorTests {
assertTrue(! (raw instanceof SubTimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = createMock(SubTimeStamped.class);
TimeStamped ts = mock(SubTimeStamped.class);
long timestamp = 111L;
expect(ts.getTimeStamp()).andReturn(timestamp);
replay(ts);
given(ts.getTimeStamp()).willReturn(timestamp);
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), SubTimeStamped.class));
SubTimeStamped tsp = (SubTimeStamped) factory.getProxy();
assertTrue(tsp.getTimeStamp() == timestamp);
verify(ts);
}
@Test
......@@ -94,18 +89,15 @@ public final class DelegatingIntroductionInterceptorTests {
assertTrue(! (raw instanceof TimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
TimeStamped ts = createMock(SubTimeStamped.class);
TimeStamped ts = mock(SubTimeStamped.class);
long timestamp = 111L;
expect(ts.getTimeStamp()).andReturn(timestamp);
replay(ts);
given(ts.getTimeStamp()).willReturn(timestamp);
factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class));
TimeStamped tsp = (TimeStamped) factory.getProxy();
assertTrue(!(tsp instanceof SubTimeStamped));
assertTrue(tsp.getTimeStamp() == timestamp);
verify(ts);
}
@Test
......
......@@ -16,8 +16,8 @@
package org.springframework.beans.factory.config;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import java.util.HashMap;
import java.util.Map;
......@@ -45,24 +45,20 @@ public final class CustomScopeConfigurerTests {
@Test
public void testWithNoScopes() throws Exception {
Scope scope = createMock(Scope.class);
replay(scope);
Scope scope = mock(Scope.class);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.postProcessBeanFactory(factory);
verify(scope);
}
@Test
public void testSunnyDayWithBonaFideScopeInstance() throws Exception {
Scope scope = createMock(Scope.class);
replay(scope);
Scope scope = mock(Scope.class);
factory.registerScope(FOO_SCOPE, scope);
Map<String, Object> scopes = new HashMap<String, Object>();
scopes.put(FOO_SCOPE, scope);
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);
figurer.postProcessBeanFactory(factory);
verify(scope);
}
@Test
......
......@@ -19,9 +19,11 @@ package org.springframework.beans.factory.config;
import java.util.Date;
import javax.inject.Provider;
import static org.easymock.EasyMock.*;
import org.junit.After;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import static test.util.TestResourceUtils.*;
......@@ -105,9 +107,8 @@ public class ObjectFactoryCreatingFactoryBeanTests {
final String targetBeanName = "singleton";
final String expectedSingleton = "Alicia Keys";
BeanFactory beanFactory = createMock(BeanFactory.class);
expect(beanFactory.getBean(targetBeanName)).andReturn(expectedSingleton);
replay(beanFactory);
BeanFactory beanFactory = mock(BeanFactory.class);
given(beanFactory.getBean(targetBeanName)).willReturn(expectedSingleton);
ObjectFactoryCreatingFactoryBean factory = new ObjectFactoryCreatingFactoryBean();
factory.setTargetBeanName(targetBeanName);
......@@ -116,8 +117,6 @@ public class ObjectFactoryCreatingFactoryBeanTests {
ObjectFactory<?> objectFactory = factory.getObject();
Object actualSingleton = objectFactory.getObject();
assertSame(expectedSingleton, actualSingleton);
verify(beanFactory);
}
@Test
......
......@@ -16,8 +16,8 @@
package org.springframework.beans.factory.config;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition;
import org.junit.Before;
......@@ -269,17 +269,13 @@ public final class ServiceLocatorFactoryBeanTests {
@Test
public void testRequiresListableBeanFactoryAndChokesOnAnythingElse() throws Exception {
final BeanFactory beanFactory = createMock(BeanFactory.class);
replay(beanFactory);
BeanFactory beanFactory = mock(BeanFactory.class);
try {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setBeanFactory(beanFactory);
} catch (FatalBeanException ex) {
// expected
}
verify(beanFactory);
}
......
......@@ -16,7 +16,10 @@
package org.springframework.beans.factory.parsing;
import static org.easymock.EasyMock.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.apache.commons.logging.Log;
import org.junit.Test;
......@@ -41,15 +44,13 @@ public final class FailFastProblemReporterTests {
Problem problem = new Problem("VGER", new Location(new DescriptiveResource("here")),
null, new IllegalArgumentException());
Log log = createMock(Log.class);
log.warn(anyObject(), isA(IllegalArgumentException.class));
replay(log);
Log log = mock(Log.class);
FailFastProblemReporter reporter = new FailFastProblemReporter();
reporter.setLogger(log);
reporter.warning(problem);
verify(log);
verify(log).warn(any(), isA(IllegalArgumentException.class));
}
}
......@@ -30,8 +30,9 @@ import java.util.Set;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.Test;
import org.mockito.Mockito;
import test.beans.GenericBean;
import test.beans.GenericIntegerBean;
import test.beans.GenericSetOfIntegerBean;
......@@ -626,10 +627,10 @@ public class BeanFactoryGenericsTests {
/**
* Tests support for parameterized {@code factory-method} declarations such
* as EasyMock's {@code createMock()} method which has the following signature.
* as Mockito {@code mock()} method which has the following signature.
*
* <pre>{@code
* public static <T> T createMock(Class<T> toMock)
* public static <T> T mock(Class<T> classToMock)
* }</pre>
*
* See SPR-9493
......@@ -637,12 +638,12 @@ public class BeanFactoryGenericsTests {
*/
@Test
public void parameterizedFactoryMethod() {
RootBeanDefinition rbd = new RootBeanDefinition(EasyMock.class);
rbd.setFactoryMethodName("createMock");
RootBeanDefinition rbd = new RootBeanDefinition(Mockito.class);
rbd.setFactoryMethodName("mock");
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("easyMock", rbd);
bf.registerBeanDefinition("mock", rbd);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertEquals(1, beans.size());
......
......@@ -16,8 +16,10 @@
package org.springframework.beans.factory.wiring;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
......@@ -32,31 +34,24 @@ import test.beans.TestBean;
public class BeanConfigurerSupportTests extends TestCase {
public void testSupplyIncompatibleBeanFactoryImplementation() throws Exception {
MockControl mock = MockControl.createControl(BeanFactory.class);
mock.replay();
try {
new StubBeanConfigurerSupport().setBeanFactory((BeanFactory) mock.getMock());
new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class));
fail("Must have thrown an IllegalArgumentException by this point (incompatible BeanFactory implementation supplied)");
}
catch (IllegalArgumentException expected) {
}
mock.verify();
}
public void testConfigureBeanDoesNothingIfBeanWiringInfoResolverResolvesToNull() throws Exception {
TestBean beanInstance = new TestBean();
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(null);
mock.replay();
BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class);
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanWiringInfoResolver(resolver);
configurer.setBeanFactory(new DefaultListableBeanFactory());
configurer.configureBean(beanInstance);
mock.verify();
verify(resolver).resolveWiringInfo(beanInstance);
assertNull(beanInstance.getName());
}
......@@ -91,19 +86,14 @@ public class BeanConfigurerSupportTests extends TestCase {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("spouse", builder.getBeanDefinition());
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, false));
mock.replay();
BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class);
given(resolver.resolveWiringInfo(beanInstance)).willReturn(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, false));
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanFactory(factory);
configurer.setBeanWiringInfoResolver(resolver);
configurer.configureBean(beanInstance);
assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
mock.verify();
}
public void testConfigureBeanPerformsAutowiringByTypeIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception {
......@@ -115,19 +105,14 @@ public class BeanConfigurerSupportTests extends TestCase {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("Mmm, I fancy a salad!", builder.getBeanDefinition());
MockControl mock = MockControl.createControl(BeanWiringInfoResolver.class);
BeanWiringInfoResolver resolver = (BeanWiringInfoResolver) mock.getMock();
resolver.resolveWiringInfo(beanInstance);
mock.setReturnValue(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false));
mock.replay();
BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class);
given(resolver.resolveWiringInfo(beanInstance)).willReturn(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false));
BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
configurer.setBeanFactory(factory);
configurer.setBeanWiringInfoResolver(resolver);
configurer.configureBean(beanInstance);
assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
mock.verify();
}
......
......@@ -21,6 +21,9 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.Arrays;
import java.util.Date;
......@@ -30,7 +33,6 @@ import java.util.Map;
import javax.sql.DataSource;
import org.easymock.MockControl;
import org.junit.Test;
import org.quartz.CronTrigger;
import org.quartz.Job;
......@@ -127,31 +129,10 @@ public class QuartzSupportTests {
trigger1.setRepeatInterval(20);
trigger1.afterPropertiesSet();
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
scheduler.getContext();
schedulerControl.setReturnValue(new SchedulerContext());
scheduler.getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getJobDetail("myJob1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.addJob(jobDetail0, true);
schedulerControl.setVoidCallable();
scheduler.scheduleJob(trigger0);
schedulerControl.setReturnValue(new Date());
scheduler.addJob(jobDetail1, true);
schedulerControl.setVoidCallable();
scheduler.scheduleJob(trigger1);
schedulerControl.setReturnValue(new Date());
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
final Scheduler scheduler = mock(Scheduler.class);
given(scheduler.getContext()).willReturn(new SchedulerContext());
given(scheduler.scheduleJob(trigger0)).willReturn(new Date());
given(scheduler.scheduleJob(trigger1)).willReturn(new Date());
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
......@@ -175,7 +156,14 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getJobDetail("myJob1", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
verify(scheduler).addJob(jobDetail0, true);
verify(scheduler).addJob(jobDetail1, true);
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
......@@ -220,33 +208,11 @@ public class QuartzSupportTests {
trigger1.setRepeatInterval(20);
trigger1.afterPropertiesSet();
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
scheduler.getContext();
schedulerControl.setReturnValue(new SchedulerContext());
scheduler.getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(new SimpleTrigger());
if (overwrite) {
scheduler.addJob(jobDetail1, true);
schedulerControl.setVoidCallable();
scheduler.rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1);
schedulerControl.setReturnValue(new Date());
}
else {
scheduler.getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
}
scheduler.addJob(jobDetail0, true);
schedulerControl.setVoidCallable();
scheduler.scheduleJob(trigger0);
schedulerControl.setReturnValue(new Date());
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
final Scheduler scheduler = mock(Scheduler.class);
given(scheduler.getContext()).willReturn(new SchedulerContext());
given(scheduler.rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1)).willReturn(new Date());
given(scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP)).willReturn(new SimpleTrigger());
given(scheduler.scheduleJob(trigger0)).willReturn(new Date());
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
......@@ -270,7 +236,18 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
if (overwrite) {
verify(scheduler).addJob(jobDetail1, true);
verify(scheduler).rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1);
}
else {
verify(scheduler).getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
}
verify(scheduler).addJob(jobDetail0, true);
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
......@@ -315,37 +292,16 @@ public class QuartzSupportTests {
trigger1.setRepeatInterval(20);
trigger1.afterPropertiesSet();
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
scheduler.getContext();
schedulerControl.setReturnValue(new SchedulerContext());
scheduler.getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(new SimpleTrigger());
final Scheduler scheduler = mock(Scheduler.class);
given(scheduler.getContext()).willReturn(new SchedulerContext());
given(scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP)).willReturn(new SimpleTrigger());
if (overwrite) {
scheduler.addJob(jobDetail1, true);
schedulerControl.setVoidCallable();
scheduler.rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1);
schedulerControl.setReturnValue(new Date());
given(scheduler.rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1)).willReturn(new Date());
}
else {
scheduler.getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
}
scheduler.addJob(jobDetail0, true);
schedulerControl.setVoidCallable();
scheduler.scheduleJob(trigger0);
schedulerControl.setThrowable(new ObjectAlreadyExistsException(""));
given(scheduler.scheduleJob(trigger0)).willThrow(new ObjectAlreadyExistsException(""));
if (overwrite) {
scheduler.rescheduleJob("myTrigger0", Scheduler.DEFAULT_GROUP, trigger0);
schedulerControl.setReturnValue(new Date());
given(scheduler.rescheduleJob("myTrigger0", Scheduler.DEFAULT_GROUP, trigger0)).willReturn(new Date());
}
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
......@@ -369,15 +325,25 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
if (overwrite) {
verify(scheduler).addJob(jobDetail1, true);
verify(scheduler).rescheduleJob("myTrigger1", Scheduler.DEFAULT_GROUP, trigger1);
}
else {
verify(scheduler).getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
}
verify(scheduler).addJob(jobDetail0, true);
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
public void testSchedulerFactoryBeanWithListeners() throws Exception {
JobFactory jobFactory = new AdaptableJobFactory();
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerListener schedulerListener = new TestSchedulerListener();
JobListener globalJobListener = new TestJobListener();
......@@ -385,24 +351,6 @@ public class QuartzSupportTests {
TriggerListener globalTriggerListener = new TestTriggerListener();
TriggerListener triggerListener = new TestTriggerListener();
scheduler.setJobFactory(jobFactory);
schedulerControl.setVoidCallable();
scheduler.addSchedulerListener(schedulerListener);
schedulerControl.setVoidCallable();
scheduler.addGlobalJobListener(globalJobListener);
schedulerControl.setVoidCallable();
scheduler.addJobListener(jobListener);
schedulerControl.setVoidCallable();
scheduler.addGlobalTriggerListener(globalTriggerListener);
schedulerControl.setVoidCallable();
scheduler.addTriggerListener(triggerListener);
schedulerControl.setVoidCallable();
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
......@@ -423,7 +371,14 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).setJobFactory(jobFactory);
verify(scheduler).addSchedulerListener(schedulerListener);
verify(scheduler).addGlobalJobListener(globalJobListener);
verify(scheduler).addJobListener(jobListener);
verify(scheduler).addGlobalTriggerListener(globalTriggerListener);
verify(scheduler).addTriggerListener(triggerListener);
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
/*public void testMethodInvocationWithConcurrency() throws Exception {
......@@ -547,31 +502,9 @@ public class QuartzSupportTests {
trigger1.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger1.setRepeatInterval(20);
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
scheduler.setJobFactory(jobFactory);
schedulerControl.setVoidCallable();
scheduler.getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getJobDetail("myJob1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
schedulerControl.setReturnValue(null);
scheduler.addJob(jobDetail0, true);
schedulerControl.setVoidCallable();
scheduler.addJob(jobDetail1, true);
schedulerControl.setVoidCallable();
scheduler.scheduleJob(trigger0);
schedulerControl.setReturnValue(new Date());
scheduler.scheduleJob(trigger1);
schedulerControl.setReturnValue(new Date());
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
final Scheduler scheduler = mock(Scheduler.class);
given(scheduler.scheduleJob(trigger0)).willReturn(new Date());
given(scheduler.scheduleJob(trigger1)).willReturn(new Date());
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
......@@ -590,7 +523,17 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).setJobFactory(jobFactory);
verify(scheduler).getJobDetail("myJob0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getJobDetail("myJob1", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger0", Scheduler.DEFAULT_GROUP);
verify(scheduler).getTrigger("myTrigger1", Scheduler.DEFAULT_GROUP);
verify(scheduler).addJob(jobDetail0, true);
verify(scheduler).addJob(jobDetail1, true);
verify(scheduler).scheduleJob(trigger0);
verify(scheduler).scheduleJob(trigger1);
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
......@@ -598,16 +541,9 @@ public class QuartzSupportTests {
TestBean tb = new TestBean("tb", 99);
StaticApplicationContext ac = new StaticApplicationContext();
MockControl schedulerControl = MockControl.createControl(Scheduler.class);
final Scheduler scheduler = (Scheduler) schedulerControl.getMock();
final Scheduler scheduler = mock(Scheduler.class);
SchedulerContext schedulerContext = new SchedulerContext();
scheduler.getContext();
schedulerControl.setReturnValue(schedulerContext, 4);
scheduler.start();
schedulerControl.setVoidCallable();
scheduler.shutdown(false);
schedulerControl.setVoidCallable();
schedulerControl.replay();
given(scheduler.getContext()).willReturn(schedulerContext);
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
@Override
......@@ -632,7 +568,8 @@ public class QuartzSupportTests {
schedulerFactoryBean.destroy();
}
schedulerControl.verify();
verify(scheduler).start();
verify(scheduler).shutdown(false);
}
@Test
......
......@@ -16,8 +16,9 @@
package org.springframework.aop.aspectj;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
......@@ -55,56 +56,44 @@ public final class AfterAdviceBindingTests {
// we need the real target too, not just the proxy...
testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();
mockCollaborator = createNiceMock(AdviceBindingCollaborator.class);
mockCollaborator = mock(AdviceBindingCollaborator.class);
afterAdviceAspect.setCollaborator(mockCollaborator);
}
@Test
public void testOneIntArg() {
mockCollaborator.oneIntArg(5);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntArg(5);
}
@Test
public void testOneObjectArgBindingProxyWithThis() {
mockCollaborator.oneObjectArg(this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanProxy);
}
@Test
public void testOneObjectArgBindingTarget() {
mockCollaborator.oneObjectArg(this.testBeanTarget);
replay(mockCollaborator);
testBeanProxy.getDoctor();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanTarget);
}
@Test
public void testOneIntAndOneObjectArgs() {
mockCollaborator.oneIntAndOneObject(5,this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntAndOneObject(5,this.testBeanProxy);
}
@Test
public void testNeedsJoinPoint() {
mockCollaborator.needsJoinPoint("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPoint("getAge");
}
@Test
public void testNeedsJoinPointStaticPart() {
mockCollaborator.needsJoinPointStaticPart("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPointStaticPart("getAge");
}
}
......@@ -16,8 +16,10 @@
package org.springframework.aop.aspectj;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import org.junit.Before;
import org.junit.Test;
......@@ -58,7 +60,7 @@ public final class AfterReturningAdviceBindingTests {
afterAdviceAspect = (AfterReturningAdviceBindingTestAspect) ctx.getBean("testAspect");
mockCollaborator = createNiceMock(AfterReturningAdviceBindingCollaborator.class);
mockCollaborator = mock(AfterReturningAdviceBindingCollaborator.class);
afterAdviceAspect.setCollaborator(mockCollaborator);
testBeanProxy = (ITestBean) ctx.getBean("testBean");
......@@ -71,106 +73,79 @@ public final class AfterReturningAdviceBindingTests {
@Test
public void testOneIntArg() {
mockCollaborator.oneIntArg(5);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntArg(5);
}
@Test
public void testOneObjectArg() {
mockCollaborator.oneObjectArg(this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanProxy);
}
@Test
public void testOneIntAndOneObjectArgs() {
mockCollaborator.oneIntAndOneObject(5,this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntAndOneObject(5,this.testBeanProxy);
}
@Test
public void testNeedsJoinPoint() {
mockCollaborator.needsJoinPoint("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPoint("getAge");
}
@Test
public void testNeedsJoinPointStaticPart() {
mockCollaborator.needsJoinPointStaticPart("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPointStaticPart("getAge");
}
@Test
public void testReturningString() {
mockCollaborator.oneString("adrian");
replay(mockCollaborator);
testBeanProxy.setName("adrian");
testBeanProxy.getName();
verify(mockCollaborator);
verify(mockCollaborator).oneString("adrian");
}
@Test
public void testReturningObject() {
mockCollaborator.oneObjectArg(this.testBeanTarget);
replay(mockCollaborator);
testBeanProxy.returnsThis();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanTarget);
}
@Test
public void testReturningBean() {
mockCollaborator.oneTestBeanArg(this.testBeanTarget);
replay(mockCollaborator);
testBeanProxy.returnsThis();
verify(mockCollaborator);
verify(mockCollaborator).oneTestBeanArg(this.testBeanTarget);
}
@Test
public void testReturningBeanArray() {
this.testBeanTarget.setSpouse(new TestBean());
ITestBean[] spouses = this.testBeanTarget.getSpouses();
mockCollaborator.testBeanArrayArg(spouses);
replay(mockCollaborator);
testBeanProxy.getSpouses();
verify(mockCollaborator);
verify(mockCollaborator).testBeanArrayArg(spouses);
}
@Test
public void testNoInvokeWhenReturningParameterTypeDoesNotMatch() {
// we need a strict mock for this...
mockCollaborator = createMock(AfterReturningAdviceBindingCollaborator.class);
afterAdviceAspect.setCollaborator(mockCollaborator);
replay(mockCollaborator);
testBeanProxy.setSpouse(this.testBeanProxy);
testBeanProxy.getSpouse();
verify(mockCollaborator);
verifyZeroInteractions(mockCollaborator);
}
@Test
public void testReturningByType() {
mockCollaborator.objectMatchNoArgs();
replay(mockCollaborator);
testBeanProxy.returnsThis();
verify(mockCollaborator);
verify(mockCollaborator).objectMatchNoArgs();
}
@Test
public void testReturningPrimitive() {
mockCollaborator.oneInt(20);
replay(mockCollaborator);
testBeanProxy.setAge(20);
testBeanProxy.haveBirthday();
verify(mockCollaborator);
verify(mockCollaborator).oneInt(20);
}
}
......
......@@ -16,9 +16,9 @@
package org.springframework.aop.aspectj;
import static org.easymock.EasyMock.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.aspectj.AfterThrowingAdviceBindingTestAspect.AfterThrowingAdviceBindingCollaborator;
......@@ -47,65 +47,49 @@ public final class AfterThrowingAdviceBindingTests {
testBean = (ITestBean) ctx.getBean("testBean");
afterThrowingAdviceAspect = (AfterThrowingAdviceBindingTestAspect) ctx.getBean("testAspect");
mockCollaborator = createNiceMock(AfterThrowingAdviceBindingCollaborator.class);
mockCollaborator = mock(AfterThrowingAdviceBindingCollaborator.class);
afterThrowingAdviceAspect.setCollaborator(mockCollaborator);
}
@After
public void tearDown() {
verify(mockCollaborator);
}
@Test(expected=Throwable.class)
public void testSimpleAfterThrowing() throws Throwable {
mockCollaborator.noArgs();
replay(mockCollaborator);
this.testBean.exceptional(new Throwable());
verify(mockCollaborator).noArgs();
}
@Test(expected=Throwable.class)
public void testAfterThrowingWithBinding() throws Throwable {
Throwable t = new Throwable();
mockCollaborator.oneThrowable(t);
replay(mockCollaborator);
this.testBean.exceptional(t);
verify(mockCollaborator).oneThrowable(t);
}
@Test(expected=Throwable.class)
public void testAfterThrowingWithNamedTypeRestriction() throws Throwable {
Throwable t = new Throwable();
// need a strict mock for this test...
mockCollaborator = createMock(AfterThrowingAdviceBindingCollaborator.class);
afterThrowingAdviceAspect.setCollaborator(mockCollaborator);
mockCollaborator.noArgs();
mockCollaborator.oneThrowable(t);
mockCollaborator.noArgsOnThrowableMatch();
replay(mockCollaborator);
this.testBean.exceptional(t);
verify(mockCollaborator).noArgs();
verify(mockCollaborator).oneThrowable(t);
verify(mockCollaborator).noArgsOnThrowableMatch();
}
@Test(expected=Throwable.class)
public void testAfterThrowingWithRuntimeExceptionBinding() throws Throwable {
RuntimeException ex = new RuntimeException();
mockCollaborator.oneRuntimeException(ex);
replay(mockCollaborator);
this.testBean.exceptional(ex);
verify(mockCollaborator).oneRuntimeException(ex);
}
@Test(expected=Throwable.class)
public void testAfterThrowingWithTypeSpecified() throws Throwable {
mockCollaborator.noArgsOnThrowableMatch();
replay(mockCollaborator);
this.testBean.exceptional(new Throwable());
verify(mockCollaborator).noArgsOnThrowableMatch();
}
@Test(expected=Throwable.class)
public void testAfterThrowingWithRuntimeTypeSpecified() throws Throwable {
mockCollaborator.noArgsOnRuntimeExceptionMatch();
replay(mockCollaborator);
this.testBean.exceptional(new RuntimeException());
verify(mockCollaborator);
verify(mockCollaborator).noArgsOnRuntimeExceptionMatch();
}
}
......
......@@ -16,8 +16,9 @@
package org.springframework.aop.aspectj;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.aspectj.lang.ProceedingJoinPoint;
import org.junit.Before;
......@@ -60,40 +61,32 @@ public class AroundAdviceBindingTests {
this.testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();
mockCollaborator = createNiceMock(AroundAdviceBindingCollaborator.class);
mockCollaborator = mock(AroundAdviceBindingCollaborator.class);
aroundAdviceAspect.setCollaborator(mockCollaborator);
}
@Test
public void testOneIntArg() {
mockCollaborator.oneIntArg(5);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntArg(5);
}
@Test
public void testOneObjectArgBoundToTarget() {
mockCollaborator.oneObjectArg(this.testBeanTarget);
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanTarget);;
}
@Test
public void testOneIntAndOneObjectArgs() {
mockCollaborator.oneIntAndOneObject(5, this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntAndOneObject(5, this.testBeanProxy);;
}
@Test
public void testJustJoinPoint() {
mockCollaborator.justJoinPoint("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).justJoinPoint("getAge");;
}
}
......
......@@ -16,8 +16,9 @@
package org.springframework.aop.aspectj;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
......@@ -60,49 +61,39 @@ public final class BeforeAdviceBindingTests {
AdviceBindingTestAspect beforeAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");
mockCollaborator = createNiceMock(AdviceBindingCollaborator.class);
mockCollaborator = mock(AdviceBindingCollaborator.class);
beforeAdviceAspect.setCollaborator(mockCollaborator);
}
@Test
public void testOneIntArg() {
mockCollaborator.oneIntArg(5);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntArg(5);
}
@Test
public void testOneObjectArgBoundToProxyUsingThis() {
mockCollaborator.oneObjectArg(this.testBeanProxy);
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).oneObjectArg(this.testBeanProxy);
}
@Test
public void testOneIntAndOneObjectArgs() {
mockCollaborator.oneIntAndOneObject(5,this.testBeanTarget);
replay(mockCollaborator);
testBeanProxy.setAge(5);
verify(mockCollaborator);
verify(mockCollaborator).oneIntAndOneObject(5,this.testBeanTarget);
}
@Test
public void testNeedsJoinPoint() {
mockCollaborator.needsJoinPoint("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPoint("getAge");
}
@Test
public void testNeedsJoinPointStaticPart() {
mockCollaborator.needsJoinPointStaticPart("getAge");
replay(mockCollaborator);
testBeanProxy.getAge();
verify(mockCollaborator);
verify(mockCollaborator).needsJoinPointStaticPart("getAge");
}
......
......@@ -16,14 +16,17 @@
package org.springframework.aop.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.lang.reflect.Method;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
/**
......@@ -39,40 +42,27 @@ public final class MethodLocatingFactoryBeanTests {
@Before
public void setUp() {
factory = new MethodLocatingFactoryBean();
// methods must set up expectations and call replay() manually for this mock
beanFactory = createMock(BeanFactory.class);
}
@After
public void tearDown() {
verify(beanFactory);
beanFactory = mock(BeanFactory.class);
}
@Test
public void testIsSingleton() {
replay(beanFactory);
assertTrue(factory.isSingleton());
}
@Test
public void testGetObjectType() {
replay(beanFactory);
assertEquals(Method.class, factory.getObjectType());
}
@Test(expected=IllegalArgumentException.class)
public void testWithNullTargetBeanName() {
replay(beanFactory);
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
}
@Test(expected=IllegalArgumentException.class)
public void testWithEmptyTargetBeanName() {
replay(beanFactory);
factory.setTargetBeanName("");
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
......@@ -80,16 +70,12 @@ public final class MethodLocatingFactoryBeanTests {
@Test(expected=IllegalArgumentException.class)
public void testWithNullTargetMethodName() {
replay(beanFactory);
factory.setTargetBeanName(BEAN_NAME);
factory.setBeanFactory(beanFactory);
}
@Test(expected=IllegalArgumentException.class)
public void testWithEmptyTargetMethodName() {
replay(beanFactory);
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("");
factory.setBeanFactory(beanFactory);
......@@ -97,20 +83,16 @@ public final class MethodLocatingFactoryBeanTests {
@Test(expected=IllegalArgumentException.class)
public void testWhenTargetBeanClassCannotBeResolved() {
expect(beanFactory.getType(BEAN_NAME)).andReturn(null);
replay(beanFactory);
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
verify(beanFactory).getType(BEAN_NAME);
}
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings("unchecked")
public void testSunnyDayPath() throws Exception {
expect((Class) beanFactory.getType(BEAN_NAME)).andReturn(String.class);
replay(beanFactory);
given(beanFactory.getType(BEAN_NAME)).willReturn((Class)String.class);
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("toString()");
factory.setBeanFactory(beanFactory);
......@@ -122,11 +104,9 @@ public final class MethodLocatingFactoryBeanTests {
}
@Test(expected=IllegalArgumentException.class)
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings("unchecked")
public void testWhereMethodCannotBeResolved() {
expect((Class) beanFactory.getType(BEAN_NAME)).andReturn(String.class);
replay(beanFactory);
given(beanFactory.getType(BEAN_NAME)).willReturn((Class)String.class);
factory.setTargetBeanName(BEAN_NAME);
factory.setMethodName("loadOfOld()");
factory.setBeanFactory(beanFactory);
......
......@@ -16,11 +16,9 @@
package org.springframework.aop.framework;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.io.Serializable;
......@@ -80,18 +78,16 @@ public final class JdkDynamicProxyTests extends AbstractAopProxyTests implements
public void testInterceptorIsInvokedWithNoTarget() throws Throwable {
// Test return value
int age = 25;
MethodInterceptor mi = createMock(MethodInterceptor.class);
MethodInterceptor mi = mock(MethodInterceptor.class);
AdvisedSupport pc = new AdvisedSupport(new Class<?>[] { ITestBean.class });
pc.addAdvice(mi);
AopProxy aop = createAopProxy(pc);
expect(mi.invoke(null)).andReturn(age);
replay(mi);
given(mi.invoke(null)).willReturn(age);
ITestBean tb = (ITestBean) aop.getProxy();
assertTrue("correct return value", tb.getAge() == age);
verify(mi);
}
public void testTargetCanGetInvocationWithPrivateClass() throws Throwable {
......
......@@ -16,8 +16,9 @@
package org.springframework.context.access;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
......@@ -32,10 +33,7 @@ public class ContextBeanFactoryReferenceTests {
@Test
public void testAllOperations() {
ConfigurableApplicationContext ctx = createMock(ConfigurableApplicationContext.class);
ctx.close();
replay(ctx);
ConfigurableApplicationContext ctx = mock(ConfigurableApplicationContext.class);
ContextBeanFactoryReference bfr = new ContextBeanFactoryReference(ctx);
......@@ -49,6 +47,6 @@ public class ContextBeanFactoryReferenceTests {
// expected
}
verify(ctx);
verify(ctx).close();
}
}
......@@ -16,10 +16,10 @@
package org.springframework.context.annotation;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.lang.instrument.ClassFileTransformer;
......@@ -40,7 +40,7 @@ public class EnableLoadTimeWeavingTests {
public void control() {
GenericXmlApplicationContext ctx =
new GenericXmlApplicationContext(getClass(), "EnableLoadTimeWeavingTests-context.xml");
ctx.getBean("loadTimeWeaver");
ctx.getBean("loadTimeWeaver", LoadTimeWeaver.class);
}
@Test
......@@ -48,7 +48,8 @@ public class EnableLoadTimeWeavingTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(EnableLTWConfig_withAjWeavingDisabled.class);
ctx.refresh();
ctx.getBean("loadTimeWeaver");
LoadTimeWeaver loadTimeWeaver = ctx.getBean("loadTimeWeaver", LoadTimeWeaver.class);
verifyZeroInteractions(loadTimeWeaver);
}
@Test
......@@ -56,7 +57,10 @@ public class EnableLoadTimeWeavingTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(EnableLTWConfig_withAjWeavingAutodetect.class);
ctx.refresh();
ctx.getBean("loadTimeWeaver");
LoadTimeWeaver loadTimeWeaver = ctx.getBean("loadTimeWeaver", LoadTimeWeaver.class);
// no expectations -> a class file transformer should NOT be added
// because no META-INF/aop.xml is present on the classpath
verifyZeroInteractions(loadTimeWeaver);
}
@Test
......@@ -64,7 +68,8 @@ public class EnableLoadTimeWeavingTests {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(EnableLTWConfig_withAjWeavingEnabled.class);
ctx.refresh();
ctx.getBean("loadTimeWeaver");
LoadTimeWeaver loadTimeWeaver = ctx.getBean("loadTimeWeaver", LoadTimeWeaver.class);
verify(loadTimeWeaver).addTransformer(isA(ClassFileTransformer.class));
}
@Configuration
......@@ -72,10 +77,7 @@ public class EnableLoadTimeWeavingTests {
static class EnableLTWConfig_withAjWeavingDisabled implements LoadTimeWeavingConfigurer {
@Override
public LoadTimeWeaver getLoadTimeWeaver() {
LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
// no expectations -> a class file transformer should NOT be added
replay(mockLTW);
return mockLTW;
return mock(LoadTimeWeaver.class);
}
}
......@@ -84,11 +86,7 @@ public class EnableLoadTimeWeavingTests {
static class EnableLTWConfig_withAjWeavingAutodetect implements LoadTimeWeavingConfigurer {
@Override
public LoadTimeWeaver getLoadTimeWeaver() {
LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
// no expectations -> a class file transformer should NOT be added
// because no META-INF/aop.xml is present on the classpath
replay(mockLTW);
return mockLTW;
return mock(LoadTimeWeaver.class);
}
}
......@@ -97,11 +95,7 @@ public class EnableLoadTimeWeavingTests {
static class EnableLTWConfig_withAjWeavingEnabled implements LoadTimeWeavingConfigurer {
@Override
public LoadTimeWeaver getLoadTimeWeaver() {
LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
mockLTW.addTransformer(isA(ClassFileTransformer.class));
expectLastCall();
replay(mockLTW);
return mockLTW;
return mock(LoadTimeWeaver.class);
}
}
}
......@@ -20,9 +20,12 @@ import java.util.HashSet;
import java.util.Set;
import org.aopalliance.intercept.MethodInvocation;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
......@@ -50,14 +53,12 @@ public class ApplicationContextEventTests {
@SuppressWarnings("unchecked")
ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
listener.onApplicationEvent(evt);
SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
smc.addApplicationListener(listener);
replay(listener);
smc.multicastEvent(evt);
verify(listener);
verify(listener).onApplicationEvent(evt);
}
@Test
......@@ -91,20 +92,18 @@ public class ApplicationContextEventTests {
@Test
public void testEventPublicationInterceptor() throws Throwable {
MethodInvocation invocation = EasyMock.createMock(MethodInvocation.class);
ApplicationContext ctx = EasyMock.createMock(ApplicationContext.class);
MethodInvocation invocation = mock(MethodInvocation.class);
ApplicationContext ctx = mock(ApplicationContext.class);
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventClass(MyEvent.class);
interceptor.setApplicationEventPublisher(ctx);
interceptor.afterPropertiesSet();
expect(invocation.proceed()).andReturn(new Object());
expect(invocation.getThis()).andReturn(new Object());
ctx.publishEvent(isA(MyEvent.class));
replay(invocation, ctx);
given(invocation.proceed()).willReturn(new Object());
given(invocation.getThis()).willReturn(new Object());
interceptor.invoke(invocation);
verify(invocation, ctx);
verify(ctx).publishEvent(isA(MyEvent.class));
}
@Test
......
......@@ -16,8 +16,8 @@
package org.springframework.context.event;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
......@@ -44,13 +44,7 @@ public class EventPublicationInterceptorTests {
@Before
public void setUp() {
publisher = createMock(ApplicationEventPublisher.class);
replay(publisher);
}
@After
public void tearDown() {
verify(publisher);
publisher = mock(ApplicationEventPublisher.class);
}
@Test(expected=IllegalArgumentException.class)
......
......@@ -16,8 +16,10 @@
package org.springframework.ejb.access;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;
......@@ -41,15 +43,14 @@ public class LocalSlsbInvokerInterceptorTests {
*/
@Test
public void testPerformsLookup() throws Exception {
LocalInterfaceWithBusinessMethods ejb = createMock(LocalInterfaceWithBusinessMethods.class);
replay(ejb);
LocalInterfaceWithBusinessMethods ejb = mock(LocalInterfaceWithBusinessMethods.class);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb);
configuredInterceptor(mockContext, jndiName);
verify(mockContext);
verify(mockContext).close();
}
@Test
......@@ -81,10 +82,8 @@ public class LocalSlsbInvokerInterceptorTests {
@Test
public void testInvokesMethodOnEjbInstance() throws Exception {
Object retVal = new Object();
LocalInterfaceWithBusinessMethods ejb = createMock(LocalInterfaceWithBusinessMethods.class);
expect(ejb.targetMethod()).andReturn(retVal);
ejb.remove();
replay(ejb);
LocalInterfaceWithBusinessMethods ejb = mock(LocalInterfaceWithBusinessMethods.class);
given(ejb.targetMethod()).willReturn(retVal);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb);
......@@ -97,17 +96,15 @@ public class LocalSlsbInvokerInterceptorTests {
assertTrue(target.targetMethod() == retVal);
verify(mockContext);
verify(ejb);
verify(mockContext).close();
verify(ejb).remove();
}
@Test
public void testInvokesMethodOnEjbInstanceWithSeparateBusinessMethods() throws Exception {
Object retVal = new Object();
LocalInterface ejb = createMock(LocalInterface.class);
expect(ejb.targetMethod()).andReturn(retVal);
ejb.remove();
replay(ejb);
LocalInterface ejb = mock(LocalInterface.class);
given(ejb.targetMethod()).willReturn(retVal);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb);
......@@ -120,14 +117,13 @@ public class LocalSlsbInvokerInterceptorTests {
assertTrue(target.targetMethod() == retVal);
verify(mockContext);
verify(ejb);
verify(mockContext).close();
verify(ejb).remove();
}
private void testException(Exception expected) throws Exception {
LocalInterfaceWithBusinessMethods ejb = createMock(LocalInterfaceWithBusinessMethods.class);
expect(ejb.targetMethod()).andThrow(expected);
replay(ejb);
LocalInterfaceWithBusinessMethods ejb = mock(LocalInterfaceWithBusinessMethods.class);
given(ejb.targetMethod()).willThrow(expected);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb);
......@@ -146,8 +142,7 @@ public class LocalSlsbInvokerInterceptorTests {
assertTrue(thrown == expected);
}
verify(mockContext);
verify(ejb);
verify(mockContext).close();
}
@Test
......@@ -157,16 +152,10 @@ public class LocalSlsbInvokerInterceptorTests {
protected Context mockContext(final String jndiName, final Object ejbInstance)
throws Exception {
final SlsbHome mockHome = createMock(SlsbHome.class);
expect(mockHome.create()).andReturn((LocalInterface)ejbInstance);
replay(mockHome);
final Context mockCtx = createMock(Context.class);
expect(mockCtx.lookup("java:comp/env/" + jndiName)).andReturn(mockHome);
mockCtx.close();
replay(mockCtx);
SlsbHome mockHome = mock(SlsbHome.class);
given(mockHome.create()).willReturn((LocalInterface)ejbInstance);
Context mockCtx = mock(Context.class);
given(mockCtx.lookup("java:comp/env/" + jndiName)).willReturn(mockHome);
return mockCtx;
}
......
......@@ -16,8 +16,11 @@
package org.springframework.ejb.access;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.lang.reflect.Proxy;
......@@ -42,14 +45,11 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
final int value = 11;
final String jndiName = "foo";
MyEjb myEjb = createMock(MyEjb.class);
expect(myEjb.getValue()).andReturn(value);
myEjb.remove();
replay(myEjb);
MyEjb myEjb = mock(MyEjb.class);
given(myEjb.getValue()).willReturn(value);
final MyHome home = createMock(MyHome.class);
expect(home.create()).andReturn(myEjb);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willReturn(myEjb);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -72,8 +72,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
assertTrue(mbm.getValue() == value);
verify(myEjb);
verify(home);
verify(myEjb).remove();
}
@Test
......@@ -81,9 +80,8 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
final int value = 11;
final String jndiName = "foo";
final MyEjb myEjb = createMock(MyEjb.class);
expect(myEjb.getValue()).andReturn(value);
replay(myEjb);
final MyEjb myEjb = mock(MyEjb.class);
given(myEjb.getValue()).willReturn(value);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -106,7 +104,6 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
assertTrue(mbm.getValue() == value);
verify(myEjb);
}
@Test
......@@ -114,9 +111,8 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
final String jndiName = "foo";
final CreateException cex = new CreateException();
final MyHome home = createMock(MyHome.class);
expect(home.create()).andThrow(cex);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willThrow(cex);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -147,8 +143,6 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
catch (EjbAccessException ex) {
assertSame(cex, ex.getCause());
}
verify(home);
}
@Test
......@@ -157,8 +151,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
// Could actually try to figure out interface from create?
final String jndiName = "foo";
final MyHome home = createMock(MyHome.class);
replay(home);
final MyHome home = mock(MyHome.class);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -188,7 +181,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests {
}
// Expect no methods on home
verify(home);
verifyZeroInteractions(home);
}
......
......@@ -16,8 +16,12 @@
package org.springframework.ejb.access;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.rmi.ConnectException;
import java.rmi.RemoteException;
......@@ -41,20 +45,12 @@ import org.springframework.remoting.RemoteAccessException;
public class SimpleRemoteSlsbInvokerInterceptorTests {
private Context mockContext(
String jndiName, RemoteInterface ejbInstance, int createCount, int lookupCount, int closeCount)
String jndiName, RemoteInterface ejbInstance)
throws Exception {
final SlsbHome mockHome = createMock(SlsbHome.class);
expect(mockHome.create()).andReturn(ejbInstance).times(createCount);
replay(mockHome);
final Context mockCtx = createMock(Context.class);
expect(mockCtx.lookup("java:comp/env/" + jndiName)).andReturn(mockHome).times(lookupCount);
mockCtx.close();
expectLastCall().times(closeCount);
replay(mockCtx);
SlsbHome mockHome = mock(SlsbHome.class);
given(mockHome.create()).willReturn(ejbInstance);
Context mockCtx = mock(Context.class);
given(mockCtx.lookup("java:comp/env/" + jndiName)).willReturn(mockHome);
return mockCtx;
}
......@@ -88,33 +84,32 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
@Test
public void testPerformsLookup() throws Exception {
RemoteInterface ejb = createMock(RemoteInterface.class);
replay(ejb);
RemoteInterface ejb = mock(RemoteInterface.class);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
configuredProxy(si, RemoteInterface.class);
verify(mockContext);
verify(mockContext).close();
}
@Test
public void testPerformsLookupWithAccessContext() throws Exception {
RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andReturn(null);
replay(ejb);
RemoteInterface ejb = mock(RemoteInterface.class);
String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 2);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
si.setExposeAccessContext(true);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
assertNull(target.targetMethod());
verify(mockContext);
verify(mockContext, times(2)).close();
verify(ejb).targetMethod();
}
@Test
......@@ -165,10 +160,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
private void doTestInvokesMethodOnEjbInstance(boolean lookupHomeOnStartup, boolean cacheHome) throws Exception {
Object retVal = new Object();
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andReturn(retVal).times(2);
ejb.remove();
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willReturn(retVal);
int lookupCount = 1;
if (!cacheHome) {
......@@ -179,7 +172,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
}
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 2, lookupCount, lookupCount);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
si.setLookupHomeOnStartup(lookupHomeOnStartup);
......@@ -189,19 +182,18 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
assertTrue(target.targetMethod() == retVal);
assertTrue(target.targetMethod() == retVal);
verify(mockContext, ejb);
verify(mockContext, times(lookupCount)).close();
verify(ejb, times(2)).remove();
}
@Test
public void testInvokesMethodOnEjbInstanceWithHomeInterface() throws Exception {
Object retVal = new Object();
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andReturn(retVal);
ejb.remove();
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willReturn(retVal);
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
si.setHomeInterface(SlsbHome.class);
......@@ -209,18 +201,18 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
assertTrue(target.targetMethod() == retVal);
verify(mockContext, ejb);
verify(mockContext).close();
verify(ejb).remove();
}
@Test
public void testInvokesMethodOnEjbInstanceWithRemoteException() throws Exception {
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andThrow(new RemoteException());
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willThrow(new RemoteException());
ejb.remove();
replay(ejb);
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
......@@ -233,7 +225,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
// expected
}
verify(mockContext, ejb);
verify(mockContext).close();
verify(ejb, times(2)).remove();
}
@Test
......@@ -259,11 +252,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
private void doTestInvokesMethodOnEjbInstanceWithConnectExceptionWithRefresh(
boolean lookupHomeOnStartup, boolean cacheHome) throws Exception {
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andThrow(new ConnectException("")).times(2);
ejb.remove();
expectLastCall().times(2);
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willThrow(new ConnectException(""));
int lookupCount = 2;
if (!cacheHome) {
......@@ -274,7 +264,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
}
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 2, lookupCount, lookupCount);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
si.setRefreshHomeOnConnectFailure(true);
......@@ -290,37 +280,35 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
// expected
}
verify(mockContext, ejb);
verify(mockContext, times(lookupCount)).close();
verify(ejb, times(2)).remove();
}
@Test
public void testInvokesMethodOnEjbInstanceWithBusinessInterface() throws Exception {
Object retVal = new Object();
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andReturn(retVal);
ejb.remove();
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willReturn(retVal);
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
BusinessInterface target = (BusinessInterface) configuredProxy(si, BusinessInterface.class);
assertTrue(target.targetMethod() == retVal);
verify(mockContext, ejb);
verify(mockContext).close();
verify(ejb).remove();
}
@Test
public void testInvokesMethodOnEjbInstanceWithBusinessInterfaceWithRemoteException() throws Exception {
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andThrow(new RemoteException());
ejb.remove();
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willThrow(new RemoteException());
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
......@@ -333,7 +321,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
// expected
}
verify(mockContext, ejb);
verify(mockContext).close();
verify(ejb).remove();
}
@Test
......@@ -347,13 +336,11 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
}
private void doTestException(Exception expected) throws Exception {
final RemoteInterface ejb = createMock(RemoteInterface.class);
expect(ejb.targetMethod()).andThrow(expected);
ejb.remove();
replay(ejb);
final RemoteInterface ejb = mock(RemoteInterface.class);
given(ejb.targetMethod()).willThrow(expected);
final String jndiName= "foobar";
Context mockContext = mockContext(jndiName, ejb, 1, 1, 1);
Context mockContext = mockContext(jndiName, ejb);
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
......@@ -366,7 +353,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
assertTrue(thrown == expected);
}
verify(mockContext, ejb);
verify(mockContext).close();
verify(ejb).remove();
}
......
......@@ -16,8 +16,11 @@
package org.springframework.ejb.access;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.lang.reflect.Proxy;
import java.rmi.RemoteException;
......@@ -56,14 +59,11 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
final int value = 11;
final String jndiName = "foo";
MyEjb myEjb = createMock(MyEjb.class);
expect(myEjb.getValue()).andReturn(value);
myEjb.remove();
replay(myEjb);
MyEjb myEjb = mock(MyEjb.class);
given(myEjb.getValue()).willReturn(value);
final MyHome home = createMock(MyHome.class);
expect(home.create()).andReturn(myEjb);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willReturn(myEjb);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -86,8 +86,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
assertEquals("Returns expected value", value, mbm.getValue());
verify(myEjb);
verify(home);
verify(myEjb).remove();
}
@Test
......@@ -95,9 +94,8 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
final int value = 11;
final String jndiName = "foo";
final MyEjb myEjb = createMock(MyEjb.class);
expect(myEjb.getValue()).andReturn(value);
replay(myEjb);
final MyEjb myEjb = mock(MyEjb.class);
given(myEjb.getValue()).willReturn(value);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -120,7 +118,6 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject();
assertTrue(Proxy.isProxyClass(mbm.getClass()));
assertEquals("Returns expected value", value, mbm.getValue());
verify(myEjb);
}
@Override
......@@ -129,16 +126,13 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
final RemoteException rex = new RemoteException();
final String jndiName = "foo";
MyEjb myEjb = createMock(MyEjb.class);
expect(myEjb.getValue()).andThrow(rex);
MyEjb myEjb = mock(MyEjb.class);
given(myEjb.getValue()).willThrow(rex);
// TODO might want to control this behaviour...
// Do we really want to call remove after a remote exception?
myEjb.remove();
replay(myEjb);
final MyHome home = createMock(MyHome.class);
expect(home.create()).andReturn(myEjb);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willReturn(myEjb);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -167,8 +161,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
catch (RemoteException ex) {
assertSame("Threw expected RemoteException", rex, ex);
}
verify(myEjb);
verify(home);
verify(myEjb).remove();
}
@Test
......@@ -176,9 +169,8 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
final String jndiName = "foo";
final CreateException cex = new CreateException();
final MyHome home = createMock(MyHome.class);
expect(home.create()).andThrow(cex);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willThrow(cex);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -209,8 +201,6 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
catch (RemoteException ex) {
// expected
}
verify(home);
}
@Test
......@@ -218,9 +208,8 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
final String jndiName = "foo";
final CreateException cex = new CreateException();
final MyHome home = createMock(MyHome.class);
expect(home.create()).andThrow(cex);
replay(home);
final MyHome home = mock(MyHome.class);
given(home.create()).willThrow(cex);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -251,8 +240,6 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
catch (RemoteAccessException ex) {
assertTrue(ex.getCause() == cex);
}
verify(home);
}
@Test
......@@ -261,8 +248,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
// Could actually try to figure out interface from create?
final String jndiName = "foo";
final MyHome home = createMock(MyHome.class);
replay(home);
final MyHome home = mock(MyHome.class);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -292,7 +278,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem
}
// Expect no methods on home
verify(home);
verifyZeroInteractions(home);
}
......
......@@ -16,154 +16,136 @@
package org.springframework.instrument.classloading.glassfish;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.lang.instrument.ClassFileTransformer;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.spi.ClassTransformer;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.instrument.classloading.LoadTimeWeaver;
// converting away from old-style EasyMock APIs was problematic with this class
// glassfish dependencies no longer on classpath
@SuppressWarnings("deprecation")
@Ignore
public class GlassFishLoadTimeWeaverTests {
private MockControl loaderCtrl;
private GlassFishClassLoaderAdapter loader;
private LoadTimeWeaver ltw;
private class DummyInstrumentableClassLoader extends SecureClassLoader {
String INSTR_CL_NAME = GlassFishClassLoaderAdapter.INSTRUMENTABLE_CLASSLOADER_GLASSFISH_V2;
public DummyInstrumentableClassLoader() {
super();
}
public DummyInstrumentableClassLoader(ClassLoader parent) {
super(parent);
}
private List<ClassTransformer> v2Transformers = new ArrayList<ClassTransformer>();
private List<ClassFileTransformer> v3Transformers = new ArrayList<ClassFileTransformer>();
public void addTransformer(ClassTransformer transformer) {
v2Transformers.add(transformer);
}
public void addTransformer(ClassFileTransformer transformer) {
v3Transformers.add(transformer);
}
public ClassLoader copy() {
return new DummyInstrumentableClassLoader();
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (INSTR_CL_NAME.equals(name)) {
return this.getClass();
}
return getClass().getClassLoader().loadClass(name);
}
}
@Before
public void setUp() throws Exception {
ltw = new GlassFishLoadTimeWeaver(new DummyInstrumentableClassLoader());
}
@After
public void tearDown() throws Exception {
loaderCtrl.verify();
ltw = null;
}
@Test
public void testGlassFishLoadTimeWeaver() {
try {
ltw = new GlassFishLoadTimeWeaver();
fail("expected exception");
} catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testGlassFishLoadTimeWeaverClassLoader() {
try {
ltw = new GlassFishLoadTimeWeaver(null);
fail("expected exception");
} catch (RuntimeException e) {
// expected
}
ClassLoader cl1 = new URLClassLoader(new URL[0]);
ClassLoader cl2 = new URLClassLoader(new URL[0], cl1);
ClassLoader cl3 = new DummyInstrumentableClassLoader(cl2);
ClassLoader cl4 = new URLClassLoader(new URL[0], cl3);
ltw = new GlassFishLoadTimeWeaver(cl4);
assertSame(cl3, ltw.getInstrumentableClassLoader());
cl1 = new URLClassLoader(new URL[0]);
cl2 = new URLClassLoader(new URL[0], cl1);
cl3 = new DummyInstrumentableClassLoader(cl2);
cl4 = new DummyInstrumentableClassLoader(cl3);
ltw = new GlassFishLoadTimeWeaver(cl4);
assertSame(cl4, ltw.getInstrumentableClassLoader());
}
@Test
public void testAddTransformer() {
ClassFileTransformer transformer = MockControl.createNiceControl(ClassFileTransformer.class).getMock();
loaderCtrl.reset();
loader.addTransformer(transformer);
loaderCtrl.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] arg0, Object[] arg1) {
for (int i = 0; i < arg0.length; i++) {
if (arg0 != null && arg0.getClass() != arg1.getClass())
return false;
}
return true;
}
public String toString(Object[] arg0) {
return Arrays.toString(arg0);
}
});
loaderCtrl.replay();
ltw.addTransformer(transformer);
}
@Test
public void testGetThrowawayClassLoader() {
loaderCtrl.reset();
ClassLoader cl = new URLClassLoader(new URL[0]);
loaderCtrl.expectAndReturn(loader.getClassLoader(), cl);
loaderCtrl.replay();
assertSame(ltw.getThrowawayClassLoader(), cl);
}
}
\ No newline at end of file
// private MockControl loaderCtrl;
// private GlassFishClassLoaderAdapter loader;
// private LoadTimeWeaver ltw;
//
// private class DummyInstrumentableClassLoader extends SecureClassLoader {
//
// String INSTR_CL_NAME = GlassFishClassLoaderAdapter.INSTRUMENTABLE_CLASSLOADER_GLASSFISH_V2;
//
// public DummyInstrumentableClassLoader() {
// super();
// }
//
// public DummyInstrumentableClassLoader(ClassLoader parent) {
// super(parent);
// }
//
// private List<ClassTransformer> v2Transformers = new ArrayList<ClassTransformer>();
// private List<ClassFileTransformer> v3Transformers = new ArrayList<ClassFileTransformer>();
//
// public void addTransformer(ClassTransformer transformer) {
// v2Transformers.add(transformer);
// }
//
// public void addTransformer(ClassFileTransformer transformer) {
// v3Transformers.add(transformer);
// }
//
// public ClassLoader copy() {
// return new DummyInstrumentableClassLoader();
// }
//
// @Override
// public Class<?> loadClass(String name) throws ClassNotFoundException {
// if (INSTR_CL_NAME.equals(name)) {
// return this.getClass();
// }
//
// return getClass().getClassLoader().loadClass(name);
// }
// }
//
// @Before
// public void setUp() throws Exception {
// ltw = new GlassFishLoadTimeWeaver(new DummyInstrumentableClassLoader());
// }
//
// @After
// public void tearDown() throws Exception {
// loaderCtrl.verify();
// ltw = null;
// }
//
// @Test
// public void testGlassFishLoadTimeWeaver() {
// try {
// ltw = new GlassFishLoadTimeWeaver();
// fail("expected exception");
// } catch (IllegalArgumentException ex) {
// // expected
// }
//
// }
//
// @Test
// public void testGlassFishLoadTimeWeaverClassLoader() {
// try {
// ltw = new GlassFishLoadTimeWeaver(null);
// fail("expected exception");
// } catch (RuntimeException e) {
// // expected
// }
//
// ClassLoader cl1 = new URLClassLoader(new URL[0]);
// ClassLoader cl2 = new URLClassLoader(new URL[0], cl1);
// ClassLoader cl3 = new DummyInstrumentableClassLoader(cl2);
// ClassLoader cl4 = new URLClassLoader(new URL[0], cl3);
//
// ltw = new GlassFishLoadTimeWeaver(cl4);
// assertSame(cl3, ltw.getInstrumentableClassLoader());
//
// cl1 = new URLClassLoader(new URL[0]);
// cl2 = new URLClassLoader(new URL[0], cl1);
// cl3 = new DummyInstrumentableClassLoader(cl2);
// cl4 = new DummyInstrumentableClassLoader(cl3);
//
// ltw = new GlassFishLoadTimeWeaver(cl4);
// assertSame(cl4, ltw.getInstrumentableClassLoader());
// }
//
// @Test
// public void testAddTransformer() {
// ClassFileTransformer transformer = MockControl.createNiceControl(ClassFileTransformer.class).getMock();
// loaderCtrl.reset();
// loader.addTransformer(transformer);
// loaderCtrl.setMatcher(new ArgumentsMatcher() {
//
// public boolean matches(Object[] arg0, Object[] arg1) {
// for (int i = 0; i < arg0.length; i++) {
// if (arg0 != null && arg0.getClass() != arg1.getClass())
// return false;
// }
// return true;
// }
//
// public String toString(Object[] arg0) {
// return Arrays.toString(arg0);
// }
//
// });
//
// loaderCtrl.replay();
//
// ltw.addTransformer(transformer);
// }
//
// @Test
// public void testGetThrowawayClassLoader() {
// loaderCtrl.reset();
// ClassLoader cl = new URLClassLoader(new URL[0]);
// loaderCtrl.expectAndReturn(loader.getClassLoader(), cl);
// loaderCtrl.replay();
//
// assertSame(ltw.getThrowawayClassLoader(), cl);
// }
}
......@@ -16,8 +16,11 @@
package org.springframework.jndi;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import javax.naming.Context;
import javax.naming.NamingException;
......@@ -383,11 +386,8 @@ public class JndiObjectFactoryBeanTests {
public void testLookupWithExposeAccessContext() throws Exception {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
TestBean tb = new TestBean();
final Context mockCtx = createMock(Context.class);
expect(mockCtx.lookup("foo")).andReturn(tb);
mockCtx.close();
expectLastCall().times(2);
replay(mockCtx);
final Context mockCtx = mock(Context.class);
given(mockCtx.lookup("foo")).willReturn(tb);
jof.setJndiTemplate(new JndiTemplate() {
@Override
protected Context createInitialContext() {
......@@ -406,7 +406,7 @@ public class JndiObjectFactoryBeanTests {
proxy.equals(proxy);
proxy.hashCode();
proxy.toString();
verify(mockCtx);
verify(mockCtx, times(2)).close();
}
}
......@@ -16,8 +16,10 @@
package org.springframework.jndi;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
......@@ -36,10 +38,8 @@ public class JndiTemplateTests {
public void testLookupSucceeds() throws Exception {
Object o = new Object();
String name = "foo";
final Context context = createMock(Context.class);
expect(context.lookup(name)).andReturn(o);
context.close();
replay(context);
final Context context = mock(Context.class);
given(context.lookup(name)).willReturn(o);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -50,17 +50,15 @@ public class JndiTemplateTests {
Object o2 = jt.lookup(name);
assertEquals(o, o2);
verify(context);
verify(context).close();
}
@Test
public void testLookupFails() throws Exception {
NameNotFoundException ne = new NameNotFoundException();
String name = "foo";
final Context context = createMock(Context.class);
expect(context.lookup(name)).andThrow(ne);
context.close();
replay(context);
final Context context = mock(Context.class);
given(context.lookup(name)).willThrow(ne);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -76,16 +74,14 @@ public class JndiTemplateTests {
catch (NameNotFoundException ex) {
// Ok
}
verify(context);
verify(context).close();
}
@Test
public void testLookupReturnsNull() throws Exception {
String name = "foo";
final Context context = createMock(Context.class);
expect(context.lookup(name)).andReturn(null);
context.close();
replay(context);
final Context context = mock(Context.class);
given(context.lookup(name)).willReturn(null);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -101,17 +97,15 @@ public class JndiTemplateTests {
catch (NameNotFoundException ex) {
// Ok
}
verify(context);
verify(context).close();
}
@Test
public void testLookupFailsWithTypeMismatch() throws Exception {
Object o = new Object();
String name = "foo";
final Context context = createMock(Context.class);
expect(context.lookup(name)).andReturn(o);
context.close();
replay(context);
final Context context = mock(Context.class);
given(context.lookup(name)).willReturn(o);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -127,17 +121,14 @@ public class JndiTemplateTests {
catch (TypeMismatchNamingException ex) {
// Ok
}
verify(context);
verify(context).close();
}
@Test
public void testBind() throws Exception {
Object o = new Object();
String name = "foo";
final Context context = createMock(Context.class);
context.bind(name, o);
context.close();
replay(context);
final Context context = mock(Context.class);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -147,17 +138,15 @@ public class JndiTemplateTests {
};
jt.bind(name, o);
verify(context);
verify(context).bind(name, o);
verify(context).close();
}
@Test
public void testRebind() throws Exception {
Object o = new Object();
String name = "foo";
final Context context = createMock(Context.class);
context.rebind(name, o);
context.close();
replay(context);
final Context context = mock(Context.class);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -167,16 +156,15 @@ public class JndiTemplateTests {
};
jt.rebind(name, o);
verify(context);
verify(context).rebind(name, o);
verify(context).close();
;
}
@Test
public void testUnbind() throws Exception {
String name = "something";
final Context context = createMock(Context.class);
context.unbind(name);
context.close();
replay(context);
final Context context = mock(Context.class);
JndiTemplate jt = new JndiTemplate() {
@Override
......@@ -186,7 +174,8 @@ public class JndiTemplateTests {
};
jt.unbind(name);
verify(context);
verify(context).unbind(name);
verify(context).close();
}
}
......@@ -19,21 +19,20 @@ package org.springframework.scheduling.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import junit.framework.AssertionFailedError;
import org.easymock.MockControl;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.task.NoOpRunnable;
import static org.mockito.Mockito.*;
/**
* @author Rick Evans
* @author Juergen Hoeller
......@@ -58,11 +57,7 @@ public class ScheduledExecutorFactoryBeanTests {
@Test
@SuppressWarnings("serial")
public void testShutdownNowIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdownNow();
mockScheduledExecutorService.setReturnValue(null);
mockScheduledExecutorService.replay();
final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@Override
......@@ -76,17 +71,13 @@ public class ScheduledExecutorFactoryBeanTests {
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
verify(executor).shutdownNow();
}
@Test
@SuppressWarnings("serial")
public void testShutdownIsPropagatedToTheExecutorOnDestroy() throws Exception {
MockControl mockScheduledExecutorService = MockControl.createNiceControl(ScheduledExecutorService.class);
final ScheduledExecutorService executor = (ScheduledExecutorService) mockScheduledExecutorService.getMock();
executor.shutdown();
mockScheduledExecutorService.setVoidCallable();
mockScheduledExecutorService.replay();
final ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() {
@Override
......@@ -101,16 +92,12 @@ public class ScheduledExecutorFactoryBeanTests {
factory.afterPropertiesSet();
factory.destroy();
mockScheduledExecutorService.verify();
verify(executor).shutdown();
}
@Test
public void testOneTimeExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
Runnable runnable = mock(Runnable.class);
ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean();
factory.setScheduledExecutorTasks(new ScheduledExecutorTask[]{
......@@ -120,18 +107,12 @@ public class ScheduledExecutorFactoryBeanTests {
pauseToLetTaskStart(1);
factory.destroy();
mockRunnable.verify();
verify(runnable).run();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
Runnable runnable = mock(Runnable.class);
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
......@@ -143,18 +124,13 @@ public class ScheduledExecutorFactoryBeanTests {
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
verify(runnable, atLeast(2)).run();
}
@Test
public void testFixedRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
Runnable runnable = mock(Runnable.class);
willThrow(new IllegalStateException()).given(runnable).run();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
......@@ -167,19 +143,13 @@ public class ScheduledExecutorFactoryBeanTests {
pauseToLetTaskStart(2);
factory.destroy();
mockRunnable.verify();
verify(runnable, atLeast(2)).run();
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectly() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setVoidCallable();
runnable.run();
mockRunnable.setVoidCallable();
mockRunnable.replay();
Runnable runnable = mock(Runnable.class);
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
......@@ -192,24 +162,15 @@ public class ScheduledExecutorFactoryBeanTests {
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
// Mock must never have been called
verify(runnable, never()).run();
}
@Ignore
@Test
public void testWithInitialDelayRepeatedExecutionIsSetUpAndFiresCorrectlyAfterException() throws Exception {
MockControl mockRunnable = MockControl.createControl(Runnable.class);
Runnable runnable = (Runnable) mockRunnable.getMock();
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
runnable.run();
mockRunnable.setThrowable(new IllegalStateException());
mockRunnable.replay();
Runnable runnable = mock(Runnable.class);
willThrow(new IllegalStateException()).given(runnable).run();
ScheduledExecutorTask task = new ScheduledExecutorTask(runnable);
task.setPeriod(500);
......@@ -223,12 +184,8 @@ public class ScheduledExecutorFactoryBeanTests {
// invoke destroy before tasks have even been scheduled...
factory.destroy();
try {
mockRunnable.verify();
fail("Mock must never have been called");
}
catch (AssertionFailedError expected) {
}
// Mock must never have been called
verify(runnable, never()).run();
}
@Test
......
......@@ -16,11 +16,13 @@
package org.springframework.scripting.bsh;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.util.Arrays;
import java.util.Collection;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.target.dynamic.Refreshable;
......@@ -189,14 +191,10 @@ public class BshScriptFactoryTests extends TestCase {
}
public void testScriptThatCompilesButIsJustPlainBad() throws Exception {
MockControl mock = MockControl.createControl(ScriptSource.class);
ScriptSource script = (ScriptSource) mock.getMock();
script.getScriptAsString();
ScriptSource script = mock(ScriptSource.class);
final String badScript = "String getMessage() { throw new IllegalArgumentException(); }";
mock.setReturnValue(badScript);
script.isModified();
mock.setReturnValue(true);
mock.replay();
given(script.getScriptAsString()).willReturn(badScript);
given(script.isModified()).willReturn(true);
BshScriptFactory factory = new BshScriptFactory(
ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX + badScript,
new Class<?>[] {Messenger.class});
......@@ -207,7 +205,6 @@ public class BshScriptFactoryTests extends TestCase {
}
catch (BshScriptUtils.BshExecutionException expected) {
}
mock.verify();
}
public void testCtorWithNullScriptSourceLocator() throws Exception {
......
......@@ -23,6 +23,8 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import groovy.lang.DelegatingMetaClass;
import groovy.lang.GroovyObject;
......@@ -30,7 +32,6 @@ import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Map;
import org.easymock.EasyMock;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
......@@ -193,11 +194,10 @@ public class GroovyScriptFactoryTests {
@Test
public void testScriptedClassThatDoesNotHaveANoArgCtor() throws Exception {
ScriptSource script = EasyMock.createMock(ScriptSource.class);
ScriptSource script = mock(ScriptSource.class);
final String badScript = "class Foo { public Foo(String foo) {}}";
EasyMock.expect(script.getScriptAsString()).andReturn(badScript);
EasyMock.expect(script.suggestedClassName()).andReturn("someName");
EasyMock.replay(script);
given(script.getScriptAsString()).willReturn(badScript);
given(script.suggestedClassName()).willReturn("someName");
GroovyScriptFactory factory = new GroovyScriptFactory(ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX
+ badScript);
try {
......@@ -206,16 +206,14 @@ public class GroovyScriptFactoryTests {
} catch (ScriptCompilationException expected) {
assertTrue(expected.contains(InstantiationException.class));
}
EasyMock.verify(script);
}
@Test
public void testScriptedClassThatHasNoPublicNoArgCtor() throws Exception {
ScriptSource script = EasyMock.createMock(ScriptSource.class);
ScriptSource script = mock(ScriptSource.class);
final String badScript = "class Foo { protected Foo() {}}";
EasyMock.expect(script.getScriptAsString()).andReturn(badScript);
EasyMock.expect(script.suggestedClassName()).andReturn("someName");
EasyMock.replay(script);
given(script.getScriptAsString()).willReturn(badScript);
given(script.suggestedClassName()).willReturn("someName");
GroovyScriptFactory factory = new GroovyScriptFactory(ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX
+ badScript);
try {
......@@ -224,7 +222,6 @@ public class GroovyScriptFactoryTests {
} catch (ScriptCompilationException expected) {
assertTrue(expected.contains(IllegalAccessException.class));
}
EasyMock.verify(script);
}
@Test
......@@ -290,15 +287,13 @@ public class GroovyScriptFactoryTests {
@Test
public void testGetScriptedObjectDoesNotChokeOnNullInterfacesBeingPassedIn() throws Exception {
ScriptSource script = EasyMock.createMock(ScriptSource.class);
EasyMock.expect(script.getScriptAsString()).andReturn("class Bar {}");
EasyMock.expect(script.suggestedClassName()).andReturn("someName");
EasyMock.replay(script);
ScriptSource script = mock(ScriptSource.class);
given(script.getScriptAsString()).willReturn("class Bar {}");
given(script.suggestedClassName()).willReturn("someName");
GroovyScriptFactory factory = new GroovyScriptFactory("a script source locator (doesn't matter here)");
Object scriptedObject = factory.getScriptedObject(script, null);
assertNotNull(scriptedObject);
EasyMock.verify(script);
}
@Test
......
......@@ -16,8 +16,8 @@
package org.springframework.scripting.support;
import static org.mockito.Mockito.mock;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.factory.BeanFactory;
......@@ -27,15 +27,12 @@ import org.springframework.beans.factory.BeanFactory;
public class RefreshableScriptTargetSourceTests extends TestCase {
public void testCreateWithNullScriptSource() throws Exception {
MockControl mockFactory = MockControl.createNiceControl(BeanFactory.class);
mockFactory.replay();
try {
new RefreshableScriptTargetSource((BeanFactory) mockFactory.getMock(), "a.bean", null, null, false);
new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false);
fail("Must have failed when passed a null ScriptSource.");
}
catch (IllegalArgumentException expected) {
}
mockFactory.verify();
}
}
......@@ -16,12 +16,14 @@
package org.springframework.scripting.support;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
......@@ -41,43 +43,29 @@ public class ResourceScriptSourceTests extends TestCase {
}
public void testDoesNotPropagateFatalExceptionOnResourceThatCannotBeResolvedToAFile() throws Exception {
MockControl mock = MockControl.createControl(Resource.class);
Resource resource = (Resource) mock.getMock();
resource.lastModified();
mock.setThrowable(new IOException());
mock.replay();
Resource resource = mock(Resource.class);
given(resource.lastModified()).willThrow(new IOException());
ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
long lastModified = scriptSource.retrieveLastModifiedTime();
assertEquals(0, lastModified);
mock.verify();
}
public void testBeginsInModifiedState() throws Exception {
MockControl mock = MockControl.createControl(Resource.class);
Resource resource = (Resource) mock.getMock();
mock.replay();
Resource resource = mock(Resource.class);
ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
assertTrue(scriptSource.isModified());
mock.verify();
}
public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception {
MockControl mock = MockControl.createControl(Resource.class);
Resource resource = (Resource) mock.getMock();
Resource resource = mock(Resource.class);
// underlying File is asked for so that the last modified time can be checked...
resource.lastModified();
mock.setReturnValue(100, 2);
// And then mock the file changing; i.e. the File says it has been modified
given(resource.lastModified()).willReturn(100L, 100L, 200L);
// does not support File-based reading; delegates to InputStream-style reading...
//resource.getFile();
//mock.setThrowable(new FileNotFoundException());
resource.getInputStream();
mock.setReturnValue(new ByteArrayInputStream(new byte[0]));
// And then mock the file changing; i.e. the File says it has been modified
resource.lastModified();
mock.setReturnValue(200);
mock.replay();
given(resource.getInputStream()).willReturn(new ByteArrayInputStream(new byte[0]));
ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified());
......@@ -85,7 +73,6 @@ public class ResourceScriptSourceTests extends TestCase {
assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
// Must now report back as having been modified
assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified());
mock.verify();
}
public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception {
......
......@@ -16,8 +16,8 @@
package org.springframework.scripting.support;
import static org.mockito.Mockito.mock;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
......@@ -75,15 +75,12 @@ public class ScriptFactoryPostProcessorTests extends TestCase {
}
public void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() throws Exception {
MockControl mock = MockControl.createControl(BeanFactory.class);
mock.replay();
try {
new ScriptFactoryPostProcessor().setBeanFactory((BeanFactory) mock.getMock());
new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class));
fail("Must have thrown exception by this point.");
}
catch (IllegalStateException expected) {
}
mock.verify();
}
public void testChangeScriptWithRefreshableBeanFunctionality() throws Exception {
......
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.build.test.mockito;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.Invocation;
/**
* General test utilities for use with {@link Mockito}.
*
* @author Phillip Webb
*/
public class MockitoUtils {
private static MockUtil mockUtil = new MockUtil();
/**
* Verify the same invocations have been applied to two mocks. This is generally not
* the preferred way test with mockito and should be avoided if possible.
* @param expected the mock containing expected invocations
* @param actual the mock containing actual invocations
* @param argumentAdapters adapters that can be used to change argument values before
* they are compared
*/
public static <T> void verifySameInvocations(T expected, T actual, InvocationArgumentsAdapter... argumentAdapters) {
List<Invocation> expectedInvocations = mockUtil.getMockHandler(expected).getInvocationContainer().getInvocations();
List<Invocation> actualInvocations = mockUtil.getMockHandler(actual).getInvocationContainer().getInvocations();
verifySameInvocations(expectedInvocations, actualInvocations, argumentAdapters);
}
private static void verifySameInvocations(List<Invocation> expectedInvocations, List<Invocation> actualInvocations, InvocationArgumentsAdapter... argumentAdapters) {
assertThat(expectedInvocations.size(), is(equalTo(actualInvocations.size())));
for (int i = 0; i < expectedInvocations.size(); i++) {
verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters);
}
}
private static void verifySameInvocation(Invocation expectedInvocation, Invocation actualInvocation, InvocationArgumentsAdapter... argumentAdapters) {
System.out.println(expectedInvocation);
System.out.println(actualInvocation);
assertThat(expectedInvocation.getMethod(), is(equalTo(actualInvocation.getMethod())));
Object[] expectedArguments = getInvocationArguments(expectedInvocation, argumentAdapters);
Object[] actualArguments = getInvocationArguments(actualInvocation, argumentAdapters);
assertThat(expectedArguments, is(equalTo(actualArguments)));
}
private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) {
Object[] arguments = invocation.getArguments();
for (InvocationArgumentsAdapter adapter : argumentAdapters) {
arguments = adapter.adaptArguments(arguments);
}
return arguments;
}
/**
* Adapter strategy that can be used to change invocation arguments.
*/
public static interface InvocationArgumentsAdapter {
/**
* Change the arguments if required
* @param arguments the source arguments
* @return updated or original arguments (never {@code null})
*/
Object[] adaptArguments(Object[] arguments);
}
}
......@@ -16,347 +16,228 @@
package org.springframework.util.xml;
import java.io.IOException;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import java.io.InputStream;
import java.util.Arrays;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.easymock.AbstractMatcher;
import org.easymock.MockControl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.build.test.mockito.MockitoUtils;
import org.springframework.build.test.mockito.MockitoUtils.InvocationArgumentsAdapter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLReaderFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public abstract class AbstractStaxXMLReaderTestCase {
protected static XMLInputFactory inputFactory;
private XMLReader standardReader;
private MockControl contentHandlerControl;
private ContentHandler contentHandler;
private ContentHandler standardContentHandler;
@Before
public void setUp() throws Exception {
inputFactory = XMLInputFactory.newInstance();
standardReader = XMLReaderFactory.createXMLReader();
contentHandlerControl = MockControl.createStrictControl(ContentHandler.class);
contentHandlerControl.setDefaultMatcher(new SaxArgumentMatcher());
ContentHandler contentHandlerMock = (ContentHandler) contentHandlerControl.getMock();
contentHandler = new CopyingContentHandler(contentHandlerMock);
standardReader.setContentHandler(contentHandler);
}
private InputStream createTestInputStream() {
return getClass().getResourceAsStream("testContentHandler.xml");
standardContentHandler = mockContentHandler();
standardReader.setContentHandler(standardContentHandler);
}
@Test
public void contentHandlerNamespacesNoPrefixes() throws SAXException, IOException, XMLStreamException {
public void contentHandlerNamespacesNoPrefixes() throws Exception {
standardReader.setFeature("http://xml.org/sax/features/namespaces", true);
standardReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
standardReader.parse(new InputSource(createTestInputStream()));
contentHandlerControl.replay();
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(createTestInputStream());
ContentHandler contentHandler = mockContentHandler();
staxXmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
staxXmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
staxXmlReader.setContentHandler(contentHandler);
staxXmlReader.parse(new InputSource());
contentHandlerControl.verify();
verifyIdenticalInvocations(standardContentHandler, contentHandler);
}
@Test
public void contentHandlerNamespacesPrefixes() throws SAXException, IOException, XMLStreamException {
public void contentHandlerNamespacesPrefixes() throws Exception {
standardReader.setFeature("http://xml.org/sax/features/namespaces", true);
standardReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
standardReader.parse(new InputSource(createTestInputStream()));
contentHandlerControl.replay();
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(createTestInputStream());
ContentHandler contentHandler = mockContentHandler();
staxXmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
staxXmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
staxXmlReader.setContentHandler(contentHandler);
staxXmlReader.parse(new InputSource());
contentHandlerControl.verify();
verifyIdenticalInvocations(standardContentHandler, contentHandler);
}
@Test
public void contentHandlerNoNamespacesPrefixes() throws SAXException, IOException, XMLStreamException {
public void contentHandlerNoNamespacesPrefixes() throws Exception {
standardReader.setFeature("http://xml.org/sax/features/namespaces", false);
standardReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
standardReader.parse(new InputSource(createTestInputStream()));
contentHandlerControl.replay();
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(createTestInputStream());
ContentHandler contentHandler = mockContentHandler();
staxXmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
staxXmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
staxXmlReader.setContentHandler(contentHandler);
staxXmlReader.parse(new InputSource());
contentHandlerControl.verify();
verifyIdenticalInvocations(standardContentHandler, contentHandler);
}
@Test
public void lexicalHandler() throws SAXException, IOException, XMLStreamException {
MockControl lexicalHandlerControl = MockControl.createStrictControl(LexicalHandler.class);
lexicalHandlerControl.setDefaultMatcher(new SaxArgumentMatcher());
LexicalHandler lexicalHandlerMock = (LexicalHandler) lexicalHandlerControl.getMock();
LexicalHandler lexicalHandler = new CopyingLexicalHandler(lexicalHandlerMock);
public void lexicalHandler() throws Exception {
Resource testLexicalHandlerXml = new ClassPathResource("testLexicalHandler.xml", getClass());
LexicalHandler expectedLexicalHandler = mockLexicalHandler();
standardReader.setContentHandler(null);
standardReader.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
standardReader.setProperty("http://xml.org/sax/properties/lexical-handler", expectedLexicalHandler);
standardReader.parse(new InputSource(testLexicalHandlerXml.getInputStream()));
lexicalHandlerControl.replay();
inputFactory.setProperty("javax.xml.stream.isCoalescing", Boolean.FALSE);
inputFactory.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", Boolean.TRUE);
inputFactory.setProperty("javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE);
inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", Boolean.FALSE);
LexicalHandler actualLexicalHandler = mockLexicalHandler();
willAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArguments()[0] = "element";
}
}).given(actualLexicalHandler).startDTD(anyString(), anyString(), anyString());
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(testLexicalHandlerXml.getInputStream());
staxXmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
staxXmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", actualLexicalHandler);
staxXmlReader.parse(new InputSource());
lexicalHandlerControl.verify();
verifyIdenticalInvocations(expectedLexicalHandler, actualLexicalHandler);
}
protected abstract AbstractStaxXMLReader createStaxXmlReader(InputStream inputStream) throws XMLStreamException;
private final LexicalHandler mockLexicalHandler() throws Exception {
LexicalHandler lexicalHandler = mock(LexicalHandler.class);
willAnswer(new CopyCharsAnswer()).given(lexicalHandler).comment(any(char[].class), anyInt(), anyInt());
return lexicalHandler;
}
/** Easymock {@code AbstractMatcher} implementation that matches SAX arguments. */
@SuppressWarnings("serial")
protected static class SaxArgumentMatcher extends AbstractMatcher {
private InputStream createTestInputStream() {
return getClass().getResourceAsStream("testContentHandler.xml");
}
@Override
public boolean matches(Object[] expected, Object[] actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
return false;
}
if (expected.length != actual.length) {
throw new IllegalArgumentException("Expected and actual arguments must have the same size");
}
if (expected.length == 3 && expected[0] instanceof char[] && expected[1] instanceof Integer &&
expected[2] instanceof Integer) {
// handling of the character(char[], int, int) methods
String expectedString = new String((char[]) expected[0], (Integer) expected[1], (Integer) expected[2]);
String actualString = new String((char[]) actual[0], (Integer) actual[1], (Integer) actual[2]);
return expectedString.equals(actualString);
}
else if (expected.length == 1 && (expected[0] instanceof Locator)) {
return true;
}
else {
return super.matches(expected, actual);
}
}
protected abstract AbstractStaxXMLReader createStaxXmlReader(InputStream inputStream) throws XMLStreamException;
@Override
protected boolean argumentMatches(Object expected, Object actual) {
if (expected instanceof char[]) {
return Arrays.equals((char[]) expected, (char[]) actual);
protected final ContentHandler mockContentHandler() throws Exception {
ContentHandler contentHandler = mock(ContentHandler.class);
willAnswer(new CopyCharsAnswer()).given(contentHandler).characters(any(char[].class), anyInt(), anyInt());
willAnswer(new CopyCharsAnswer()).given(contentHandler).ignorableWhitespace(any(char[].class), anyInt(), anyInt());
willAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
invocation.getArguments()[3] = new AttributesImpl((Attributes) invocation.getArguments()[3]);
return null;
}
else if (expected instanceof Attributes) {
Attributes expectedAttributes = (Attributes) expected;
Attributes actualAttributes = (Attributes) actual;
if (expectedAttributes.getLength() != actualAttributes.getLength()) {
return false;
}
for (int i = 0; i < expectedAttributes.getLength(); i++) {
boolean found = false;
for (int j = 0; j < actualAttributes.getLength(); j++) {
if (expectedAttributes.getURI(i).equals(actualAttributes.getURI(j)) &&
expectedAttributes.getQName(i).equals(actualAttributes.getQName(j)) &&
expectedAttributes.getType(i).equals(actualAttributes.getType(j)) &&
expectedAttributes.getValue(i).equals(actualAttributes.getValue(j))) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
else {
return super.argumentMatches(expected, actual);
}
}
}).given(contentHandler).startElement(anyString(), anyString(), anyString(), any(Attributes.class));
return contentHandler;
}
@Override
public String toString(Object[] arguments) {
if (arguments != null && arguments.length == 3 && arguments[0] instanceof char[] &&
arguments[1] instanceof Integer && arguments[2] instanceof Integer) {
return new String((char[]) arguments[0], (Integer) arguments[1], (Integer) arguments[2]);
}
else {
return super.toString(arguments);
}
}
protected <T> void verifyIdenticalInvocations(T expected, T actual) {
MockitoUtils.verifySameInvocations(expected, actual,
new SkipLocatorArgumentsAdapter(), new CharArrayToStringAdapter(), new PartialAttributesAdapter());
}
@Override
protected String argumentToString(Object argument) {
if (argument instanceof char[]) {
char[] array = (char[]) argument;
StringBuilder buffer = new StringBuilder();
for (char anArray : array) {
buffer.append(anArray);
}
return buffer.toString();
}
else if (argument instanceof Attributes) {
Attributes attributes = (Attributes) argument;
StringBuilder buffer = new StringBuilder("[");
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getURI(i).length() != 0) {
buffer.append('{');
buffer.append(attributes.getURI(i));
buffer.append('}');
}
if (attributes.getQName(i).length() != 0) {
buffer.append(attributes.getQName(i));
}
buffer.append('=');
buffer.append(attributes.getValue(i));
if (i < attributes.getLength() - 1) {
buffer.append(", ");
}
private static class SkipLocatorArgumentsAdapter implements InvocationArgumentsAdapter {
public Object[] adaptArguments(Object[] arguments) {
for(int i=0; i<arguments.length; i++) {
if(arguments[i] instanceof Locator) {
arguments[i] = null;
}
buffer.append(']');
return buffer.toString();
}
else if (argument instanceof Locator) {
Locator locator = (Locator) argument;
StringBuilder buffer = new StringBuilder("[");
buffer.append(locator.getLineNumber());
buffer.append(',');
buffer.append(locator.getColumnNumber());
buffer.append(']');
return buffer.toString();
}
else {
return super.argumentToString(argument);
}
return arguments;
}
}
private static class CopyingContentHandler implements ContentHandler {
private final ContentHandler wrappee;
private CopyingContentHandler(ContentHandler wrappee) {
this.wrappee = wrappee;
}
public void setDocumentLocator(Locator locator) {
wrappee.setDocumentLocator(locator);
}
public void startDocument() throws SAXException {
wrappee.startDocument();
}
public void endDocument() throws SAXException {
wrappee.endDocument();
}
public void startPrefixMapping(String prefix, String uri) throws SAXException {
wrappee.startPrefixMapping(prefix, uri);
}
public void endPrefixMapping(String prefix) throws SAXException {
wrappee.endPrefixMapping(prefix);
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
wrappee.startElement(uri, localName, qName, new AttributesImpl(attributes));
}
public void endElement(String uri, String localName, String qName) throws SAXException {
wrappee.endElement(uri, localName, qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
wrappee.characters(copy(ch), start, length);
}
public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
}
public void processingInstruction(String target, String data) throws SAXException {
wrappee.processingInstruction(target, data);
}
public void skippedEntity(String name) throws SAXException {
wrappee.skippedEntity(name);
private static class CharArrayToStringAdapter implements InvocationArgumentsAdapter {
public Object[] adaptArguments(Object[] arguments) {
if(arguments.length == 3 && arguments[0] instanceof char[]
&& arguments[1] instanceof Integer && arguments[2] instanceof Integer) {
return new Object[] {new String((char[]) arguments[0], (Integer) arguments[1], (Integer) arguments[2])};
}
return arguments;
}
}
private static class CopyingLexicalHandler implements LexicalHandler {
private final LexicalHandler wrappee;
private CopyingLexicalHandler(LexicalHandler wrappee) {
this.wrappee = wrappee;
}
public void startDTD(String name, String publicId, String systemId) throws SAXException {
wrappee.startDTD("element", publicId, systemId);
private static class PartialAttributesAdapter implements InvocationArgumentsAdapter {
public Object[] adaptArguments(Object[] arguments) {
for (int i = 0; i < arguments.length; i++) {
if(arguments[i] instanceof Attributes) {
arguments[i] = new PartialAttributes((Attributes) arguments[i]);
}
};
return arguments;
}
}
public void endDTD() throws SAXException {
wrappee.endDTD();
private static class CopyCharsAnswer implements Answer<Object> {
public Object answer(InvocationOnMock invocation) throws Throwable {
char[] chars = (char[]) invocation.getArguments()[0];
char[] copy = new char[chars.length];
System.arraycopy(chars, 0, copy, 0, chars.length);
invocation.getArguments()[0] = copy;
return null;
}
}
public void startEntity(String name) throws SAXException {
wrappee.startEntity(name);
}
private static class PartialAttributes {
public void endEntity(String name) throws SAXException {
wrappee.endEntity(name);
}
private Attributes attributes;
public void startCDATA() throws SAXException {
wrappee.startCDATA();
public PartialAttributes(Attributes attributes) {
this.attributes = attributes;
}
public void endCDATA() throws SAXException {
wrappee.endCDATA();
@Override
public int hashCode() {
return 1;
}
public void comment(char ch[], int start, int length) throws SAXException {
wrappee.comment(copy(ch), start, length);
@Override
public boolean equals(Object obj) {
Attributes other = ((PartialAttributes) obj).attributes;
for (int i = 0; i < other.getLength(); i++) {
boolean found = false;
for (int j = 0; j < attributes.getLength(); j++) {
if (other.getURI(i).equals(attributes.getURI(j))
&& other.getQName(i).equals(attributes.getQName(j))
&& other.getType(i).equals(attributes.getType(j))
&& other.getValue(i).equals(attributes.getValue(j))) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
}
private static char[] copy(char[] ch) {
char[] copy = new char[ch.length];
System.arraycopy(ch, 0, copy, 0, ch.length);
return copy;
}
}
......@@ -16,13 +16,15 @@
package org.springframework.util.xml;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import org.easymock.MockControl;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.AttributesImpl;
......@@ -41,21 +43,13 @@ public class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTestCase {
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(CONTENT));
eventReader.nextTag(); // skip to root
StaxEventXMLReader xmlReader = new StaxEventXMLReader(eventReader);
MockControl mockControl = MockControl.createStrictControl(ContentHandler.class);
mockControl.setDefaultMatcher(new SaxArgumentMatcher());
ContentHandler contentHandlerMock = (ContentHandler) mockControl.getMock();
contentHandlerMock.startDocument();
contentHandlerMock.startElement("http://springframework.org/spring-ws", "child", "child", new AttributesImpl());
contentHandlerMock.endElement("http://springframework.org/spring-ws", "child", "child");
contentHandlerMock.endDocument();
xmlReader.setContentHandler(contentHandlerMock);
mockControl.replay();
ContentHandler contentHandler = mock(ContentHandler.class);
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource());
mockControl.verify();
verify(contentHandler).startDocument();
verify(contentHandler).startElement("http://springframework.org/spring-ws", "child", "child", new AttributesImpl());
verify(contentHandler).endElement("http://springframework.org/spring-ws", "child", "child");
verify(contentHandler).endDocument();
}
}
......@@ -23,12 +23,17 @@ import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.easymock.MockControl;
import static org.junit.Assert.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.Locator;
public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase {
......@@ -51,22 +56,15 @@ public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase {
streamReader.getName());
StaxStreamXMLReader xmlReader = new StaxStreamXMLReader(streamReader);
MockControl mockControl = MockControl.createStrictControl(ContentHandler.class);
mockControl.setDefaultMatcher(new SaxArgumentMatcher());
ContentHandler contentHandlerMock = (ContentHandler) mockControl.getMock();
contentHandlerMock.setDocumentLocator(null);
mockControl.setMatcher(MockControl.ALWAYS_MATCHER);
contentHandlerMock.startDocument();
contentHandlerMock.startElement("http://springframework.org/spring-ws", "child", "child", new AttributesImpl());
contentHandlerMock.endElement("http://springframework.org/spring-ws", "child", "child");
contentHandlerMock.endDocument();
xmlReader.setContentHandler(contentHandlerMock);
mockControl.replay();
ContentHandler contentHandler = mock(ContentHandler.class);
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource());
mockControl.verify();
}
verify(contentHandler).setDocumentLocator(any(Locator.class));
verify(contentHandler).startDocument();
verify(contentHandler).startElement(eq("http://springframework.org/spring-ws"), eq("child"), eq("child"), any(Attributes.class));
verify(contentHandler).endElement("http://springframework.org/spring-ws", "child", "child");
verify(contentHandler).endDocument();
}
}
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.build.test.hamcrest;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
* Additional hamcrest matchers.
*
* @author Phillip Webb
*/
public class Matchers {
/**
* Create a matcher that wrapps the specified matcher and tests against the
* {@link Throwable#getCause() cause} of an exception. If the item tested
* is {@code null} not a {@link Throwable} the wrapped matcher will be called
* with a {@code null} item.
*
* <p>Often useful when working with JUnit {@link ExpectedException}
* {@link Rule @Rule}s, for example:
* <pre>
* thrown.expect(DataAccessException.class);
* thrown.except(exceptionCause(isA(SQLException.class)));
* </pre>
*
* @param matcher the matcher to wrap (must not be null)
* @return a matcher that tests using the exception cause
*/
@SuppressWarnings("unchecked")
public static <T> Matcher<T> exceptionCause(final Matcher<T> matcher) {
return (Matcher<T>) new BaseMatcher<Object>() {
@Override
public boolean matches(Object item) {
Throwable cause = null;
if(item != null && item instanceof Throwable) {
cause = ((Throwable)item).getCause();
}
return matcher.matches(cause);
}
@Override
public void describeTo(Description description) {
description.appendText("exception cause ").appendDescriptionOf(matcher);
}
};
}
}
/*
* AbstractJdbcTests.java
*
* Copyright (C) 2002 by Interprise Software. All rights reserved.
*/
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc;
import java.sql.Connection;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
/**
* @author Trevor D. Cook
*/
public abstract class AbstractJdbcTests extends TestCase {
protected MockControl ctrlDataSource;
protected DataSource mockDataSource;
protected MockControl ctrlConnection;
protected Connection mockConnection;
/**
* Set to true if the user wants verification, indicated
* by a call to replay(). We need to make this optional,
* otherwise we setUp() will always result in verification failures
*/
private boolean shouldVerify;
@Override
protected void setUp() throws Exception {
this.shouldVerify = false;
super.setUp();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
}
protected void replay() {
ctrlDataSource.replay();
ctrlConnection.replay();
this.shouldVerify = true;
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
// we shouldn't verify unless the user called replay()
if (shouldVerify()) {
ctrlDataSource.verify();
//ctrlConnection.verify();
}
}
protected boolean shouldVerify() {
return this.shouldVerify;
}
}
......@@ -16,6 +16,12 @@
package org.springframework.jdbc.core;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
......@@ -23,9 +29,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.Person;
......@@ -39,254 +42,16 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
*
* @author Thomas Risberg
*/
public abstract class AbstractRowMapperTests extends TestCase {
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
protected MockControl conControl;
protected Connection con;
protected MockControl conControl2;
protected Connection con2;
protected MockControl conControl3;
protected Connection con3;
protected MockControl rsmdControl;
protected ResultSetMetaData rsmd;
protected MockControl rsControl;
protected ResultSet rs;
protected MockControl stmtControl;
protected Statement stmt;
protected JdbcTemplate jdbcTemplate;
protected MockControl rsmdControl2;
protected ResultSetMetaData rsmd2;
protected MockControl rsControl2;
protected ResultSet rs2;
protected MockControl stmtControl2;
protected Statement stmt2;
protected JdbcTemplate jdbcTemplate2;
protected MockControl rsmdControl3;
protected ResultSetMetaData rsmd3;
protected MockControl rsControl3;
protected ResultSet rs3;
protected MockControl stmtControl3;
protected Statement stmt3;
protected JdbcTemplate jdbcTemplate3;
@Override
protected void setUp() throws SQLException {
conControl = MockControl.createControl(Connection.class);
con = (Connection) conControl.getMock();
con.isClosed();
conControl.setDefaultReturnValue(false);
rsmdControl = MockControl.createControl(ResultSetMetaData.class);
rsmd = (ResultSetMetaData)rsmdControl.getMock();
rsmd.getColumnCount();
rsmdControl.setReturnValue(4, 1);
rsmd.getColumnLabel(1);
rsmdControl.setReturnValue("name", 1);
rsmd.getColumnLabel(2);
rsmdControl.setReturnValue("age", 1);
rsmd.getColumnLabel(3);
rsmdControl.setReturnValue("birth_date", 1);
rsmd.getColumnLabel(4);
rsmdControl.setReturnValue("balance", 1);
rsmdControl.replay();
rsControl = MockControl.createControl(ResultSet.class);
rs = (ResultSet) rsControl.getMock();
rs.getMetaData();
rsControl.setReturnValue(rsmd, 1);
rs.next();
rsControl.setReturnValue(true, 1);
rs.getString(1);
rsControl.setReturnValue("Bubba", 1);
rs.wasNull();
rsControl.setReturnValue(false, 1);
rs.getLong(2);
rsControl.setReturnValue(22, 1);
rs.getTimestamp(3);
rsControl.setReturnValue(new Timestamp(1221222L), 1);
rs.getBigDecimal(4);
rsControl.setReturnValue(new BigDecimal("1234.56"), 1);
rs.next();
rsControl.setReturnValue(false, 1);
rs.close();
rsControl.setVoidCallable(1);
rsControl.replay();
stmtControl = MockControl.createControl(Statement.class);
stmt = (Statement) stmtControl.getMock();
con.createStatement();
conControl.setReturnValue(stmt, 1);
stmt.executeQuery("select name, age, birth_date, balance from people");
stmtControl.setReturnValue(rs, 1);
if (debugEnabled) {
stmt.getWarnings();
stmtControl.setReturnValue(null, 1);
}
stmt.close();
stmtControl.setVoidCallable(1);
conControl.replay();
stmtControl.replay();
conControl2 = MockControl.createControl(Connection.class);
con2 = (Connection) conControl2.getMock();
con2.isClosed();
conControl2.setDefaultReturnValue(false);
rsmdControl2 = MockControl.createControl(ResultSetMetaData.class);
rsmd2 = (ResultSetMetaData)rsmdControl2.getMock();
rsmd2.getColumnCount();
rsmdControl2.setReturnValue(4, 2);
rsmd2.getColumnLabel(1);
rsmdControl2.setReturnValue("name", 2);
rsmd2.getColumnLabel(2);
rsmdControl2.setReturnValue("age", 2);
rsmd2.getColumnLabel(3);
rsmdControl2.setReturnValue("birth_date", 1);
rsmd2.getColumnLabel(4);
rsmdControl2.setReturnValue("balance", 1);
rsmdControl2.replay();
rsControl2 = MockControl.createControl(ResultSet.class);
rs2 = (ResultSet) rsControl2.getMock();
rs2.getMetaData();
rsControl2.setReturnValue(rsmd2, 2);
rs2.next();
rsControl2.setReturnValue(true, 2);
rs2.getString(1);
rsControl2.setReturnValue("Bubba", 2);
rs2.wasNull();
rsControl2.setReturnValue(true, 2);
rs2.getLong(2);
rsControl2.setReturnValue(0, 2);
rs2.getTimestamp(3);
rsControl2.setReturnValue(new Timestamp(1221222L), 1);
rs2.getBigDecimal(4);
rsControl2.setReturnValue(new BigDecimal("1234.56"), 1);
rs2.next();
rsControl2.setReturnValue(false, 1);
rs2.close();
rsControl2.setVoidCallable(2);
rsControl2.replay();
stmtControl2 = MockControl.createControl(Statement.class);
stmt2 = (Statement) stmtControl2.getMock();
con2.createStatement();
conControl2.setReturnValue(stmt2, 2);
stmt2.executeQuery("select name, null as age, birth_date, balance from people");
stmtControl2.setReturnValue(rs2, 2);
if (debugEnabled) {
stmt2.getWarnings();
stmtControl2.setReturnValue(null, 2);
}
stmt2.close();
stmtControl2.setVoidCallable(2);
conControl2.replay();
stmtControl2.replay();
conControl3 = MockControl.createControl(Connection.class);
con3 = (Connection) conControl3.getMock();
con3.isClosed();
conControl3.setDefaultReturnValue(false);
rsmdControl3 = MockControl.createControl(ResultSetMetaData.class);
rsmd3 = (ResultSetMetaData)rsmdControl3.getMock();
rsmd3.getColumnCount();
rsmdControl3.setReturnValue(4, 1);
rsmd3.getColumnLabel(1);
rsmdControl3.setReturnValue("Last Name", 1);
rsmd3.getColumnLabel(2);
rsmdControl3.setReturnValue("age", 1);
rsmd3.getColumnLabel(3);
rsmdControl3.setReturnValue("birth_date", 1);
rsmd3.getColumnLabel(4);
rsmdControl3.setReturnValue("balance", 1);
rsmdControl3.replay();
rsControl3 = MockControl.createControl(ResultSet.class);
rs3 = (ResultSet) rsControl3.getMock();
rs3.getMetaData();
rsControl3.setReturnValue(rsmd3, 1);
rs3.next();
rsControl3.setReturnValue(true, 1);
rs3.getString(1);
rsControl3.setReturnValue("Gagarin", 1);
rs3.wasNull();
rsControl3.setReturnValue(false, 1);
rs3.getLong(2);
rsControl3.setReturnValue(22, 1);
rs3.getTimestamp(3);
rsControl3.setReturnValue(new Timestamp(1221222L), 1);
rs3.getBigDecimal(4);
rsControl3.setReturnValue(new BigDecimal("1234.56"), 1);
rs3.next();
rsControl3.setReturnValue(false, 1);
rs3.close();
rsControl3.setVoidCallable(1);
rsControl3.replay();
stmtControl3 = MockControl.createControl(Statement.class);
stmt3 = (Statement) stmtControl3.getMock();
con3.createStatement();
conControl3.setReturnValue(stmt3, 1);
stmt3.executeQuery("select last_name as \"Last Name\", age, birth_date, balance from people");
stmtControl3.setReturnValue(rs3, 1);
if (debugEnabled) {
stmt3.getWarnings();
stmtControl3.setReturnValue(null, 1);
}
stmt3.close();
stmtControl3.setVoidCallable(1);
public abstract class AbstractRowMapperTests {
conControl3.replay();
stmtControl3.replay();
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
jdbcTemplate2 = new JdbcTemplate();
jdbcTemplate2.setDataSource(new SingleConnectionDataSource(con2, false));
jdbcTemplate2.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate2.afterPropertiesSet();
jdbcTemplate3 = new JdbcTemplate();
jdbcTemplate3.setDataSource(new SingleConnectionDataSource(con3, false));
jdbcTemplate3.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate3.afterPropertiesSet();
}
protected void verifyPerson(Person bean) {
verify();
protected void verifyPerson(Person bean) throws Exception {
assertEquals("Bubba", bean.getName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
protected void verifyPersonWithZeroAge(Person bean) {
conControl2.verify();
rsControl2.verify();
rsmdControl2.verify();
stmtControl2.verify();
assertEquals("Bubba", bean.getName());
assertEquals(0L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
protected void verifyConcretePerson(ConcretePerson bean) {
verify();
protected void verifyConcretePerson(ConcretePerson bean) throws Exception {
assertEquals("Bubba", bean.getName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
......@@ -294,21 +59,68 @@ public abstract class AbstractRowMapperTests extends TestCase {
}
protected void verifySpacePerson(SpacePerson bean) {
conControl3.verify();
rsControl3.verify();
rsmdControl3.verify();
stmtControl3.verify();
assertEquals("Gagarin", bean.getLastName());
assertEquals("Bubba", bean.getLastName());
assertEquals(22L, bean.getAge());
assertEquals(new java.util.Date(1221222L), bean.getBirthDate());
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
}
private void verify() {
conControl.verify();
rsControl.verify();
rsmdControl.verify();
stmtControl.verify();
}
protected static enum MockType {ONE,TWO,THREE};
protected static class Mock {
private Connection connection;
private ResultSetMetaData resultSetMetaData;
private ResultSet resultSet;
private Statement statement;
private JdbcTemplate jdbcTemplate;
public Mock() throws Exception {
this(MockType.ONE);
}
public Mock(MockType type)
throws Exception {
connection = mock(Connection.class);
statement = mock(Statement.class);
resultSet = mock(ResultSet.class);
resultSetMetaData = mock(ResultSetMetaData.class);
given(connection.createStatement()).willReturn(statement);
given(statement.executeQuery(anyString())).willReturn(resultSet);
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getString(1)).willReturn("Bubba");
given(resultSet.getLong(2)).willReturn(22L);
given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);
given(resultSetMetaData.getColumnCount()).willReturn(4);
given(resultSetMetaData.getColumnLabel(1)).willReturn(
type == MockType.THREE ? "Last Name" : "name");
given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
jdbcTemplate.afterPropertiesSet();
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void verifyClosed() throws Exception {
verify(resultSet).close();
verify(statement).close();
}
}
}
package org.springframework.jdbc.core;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.easymock.MockControl;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
/**
* @author Thomas Risberg
*/
public abstract class BatchUpdateTestHelper {
public static void prepareBatchUpdateMocks(String sqlToUse, Object ids, int[] sqlTypes,
int[] rowsAffected,
MockControl ctrlDataSource, DataSource mockDataSource, MockControl ctrlConnection, Connection mockConnection,
MockControl ctrlPreparedStatement,
PreparedStatement mockPreparedStatement, MockControl ctrlDatabaseMetaData, DatabaseMetaData mockDatabaseMetaData)
throws SQLException {
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(null);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
mockPreparedStatement.getConnection();
ctrlPreparedStatement.setReturnValue(mockConnection);
int idLength = 0;
if (ids instanceof SqlParameterSource[]) {
idLength = ((SqlParameterSource[])ids).length;
}
else if (ids instanceof Map[]) {
idLength = ((Map[])ids).length;
}
else {
idLength = ((List)ids).size();
}
for (int i = 0; i < idLength; i++) {
if (ids instanceof SqlParameterSource[]) {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"), sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"));
}
}
else if (ids instanceof Map[]) {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"), sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"));
}
}
else {
if (sqlTypes != null) {
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0], sqlTypes[0]);
}
else {
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0]);
}
}
ctrlPreparedStatement.setVoidCallable();
mockPreparedStatement.addBatch();
ctrlPreparedStatement.setVoidCallable();
}
mockPreparedStatement.executeBatch();
ctrlPreparedStatement.setReturnValue(rowsAffected);
if (LogFactory.getLog(JdbcTemplate.class).isDebugEnabled()) {
mockPreparedStatement.getWarnings();
ctrlPreparedStatement.setReturnValue(null);
}
mockPreparedStatement.close();
ctrlPreparedStatement.setVoidCallable();
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MySQL");
mockDatabaseMetaData.supportsBatchUpdates();
ctrlDatabaseMetaData.setReturnValue(true);
mockConnection.prepareStatement(sqlToUse);
ctrlConnection.setReturnValue(mockPreparedStatement);
mockConnection.getMetaData();
ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
}
public static void replayBatchUpdateMocks(MockControl ctrlDataSource,
MockControl ctrlConnection,
MockControl ctrlPreparedStatement,
MockControl ctrlDatabaseMetaData) {
ctrlPreparedStatement.replay();
ctrlDatabaseMetaData.replay();
ctrlDataSource.replay();
ctrlConnection.replay();
}
public static void verifyBatchUpdateMocks(MockControl ctrlPreparedStatement, MockControl ctrlDatabaseMetaData) {
ctrlPreparedStatement.verify();
ctrlDatabaseMetaData.verify();
}
}
......@@ -16,15 +16,19 @@
package org.springframework.jdbc.core;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.test.ConcretePerson;
import org.springframework.jdbc.core.test.ExtendedPerson;
import org.springframework.jdbc.core.test.Person;
import org.springframework.jdbc.core.test.SpacePerson;
import org.springframework.beans.TypeMismatchException;
/**
* @author Thomas Risberg
......@@ -32,89 +36,94 @@ import org.springframework.beans.TypeMismatchException;
*/
public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
public void testOverridingClassDefinedForMapping() {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testOverridingDifferentClassDefinedForMapping() {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
try {
mapper.setMappedClass(Long.class);
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
}
try {
mapper.setMappedClass(Person.class);
}
catch (InvalidDataAccessApiUsageException ex) {
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
}
thrown.expect(InvalidDataAccessApiUsageException.class);
mapper.setMappedClass(Long.class);
}
@Test
public void testOverridingSameClassDefinedForMapping() {
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
mapper.setMappedClass(Person.class);
}
public void testStaticQueryWithRowMapper() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(Person.class));
@Test
public void testStaticQueryWithRowMapper() throws Exception {
Mock mock = new Mock();
List<Person> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<Person>(Person.class));
assertEquals(1, result.size());
Person bean = (Person) result.get(0);
verifyPerson(bean);
verifyPerson(result.get(0));
mock.verifyClosed();
}
public void testMappingWithInheritance() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ConcretePerson.class));
@Test
public void testMappingWithInheritance() throws Exception {
Mock mock = new Mock();
List<ConcretePerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ConcretePerson>(ConcretePerson.class));
assertEquals(1, result.size());
ConcretePerson bean = (ConcretePerson) result.get(0);
verifyConcretePerson(bean);
verifyConcretePerson(result.get(0));
mock.verifyClosed();
}
public void testMappingWithNoUnpopulatedFieldsFound() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ConcretePerson.class, true));
@Test
public void testMappingWithNoUnpopulatedFieldsFound() throws Exception {
Mock mock = new Mock();
List<ConcretePerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ConcretePerson>(ConcretePerson.class, true));
assertEquals(1, result.size());
ConcretePerson bean = (ConcretePerson) result.get(0);
verifyConcretePerson(bean);
verifyConcretePerson(result.get(0));
mock.verifyClosed();
}
public void testMappingWithUnpopulatedFieldsNotChecked() throws SQLException {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ExtendedPerson.class));
@Test
public void testMappingWithUnpopulatedFieldsNotChecked() throws Exception {
Mock mock = new Mock();
List<ExtendedPerson> result = mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ExtendedPerson>(ExtendedPerson.class));
assertEquals(1, result.size());
ExtendedPerson bean = (ExtendedPerson) result.get(0);
ExtendedPerson bean = result.get(0);
verifyConcretePerson(bean);
mock.verifyClosed();
}
public void testMappingWithUnpopulatedFieldsNotAccepted() throws SQLException {
try {
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
new BeanPropertyRowMapper(ExtendedPerson.class, true));
fail("Should have thrown InvalidDataAccessApiUsageException because of missing field");
}
catch (InvalidDataAccessApiUsageException ex) {
// expected
}
@Test
public void testMappingWithUnpopulatedFieldsNotAccepted() throws Exception {
Mock mock = new Mock();
thrown.expect(InvalidDataAccessApiUsageException.class);
mock.getJdbcTemplate().query(
"select name, age, birth_date, balance from people",
new BeanPropertyRowMapper<ExtendedPerson>(ExtendedPerson.class, true));
}
public void testMappingNullValue() throws SQLException {
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
try {
List result1 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
mapper);
fail("Should have thrown TypeMismatchException because of null value");
}
catch (TypeMismatchException ex) {
// expected
}
mapper.setPrimitivesDefaultedForNullValue(true);
List result2 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
mapper);
assertEquals(1, result2.size());
Person bean = (Person) result2.get(0);
verifyPersonWithZeroAge(bean);
@Test
public void testMappingNullValue() throws Exception {
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
Mock mock = new Mock(MockType.TWO);
thrown.expect(TypeMismatchException.class);
mock.getJdbcTemplate().query(
"select name, null as age, birth_date, balance from people", mapper);
}
public void testQueryWithSpaceInColumnName() throws SQLException {
List result = jdbcTemplate3.query("select last_name as \"Last Name\", age, birth_date, balance from people",
new BeanPropertyRowMapper(SpacePerson.class));
@Test
public void testQueryWithSpaceInColumnName() throws Exception {
Mock mock = new Mock(MockType.THREE);
List<SpacePerson> result = mock.getJdbcTemplate().query(
"select last_name as \"Last Name\", age, birth_date, balance from people",
new BeanPropertyRowMapper<SpacePerson>(SpacePerson.class));
assertEquals(1, result.size());
SpacePerson bean = (SpacePerson) result.get(0);
verifySpacePerson(bean);
verifySpacePerson(result.get(0));
mock.verifyClosed();
}
}
package org.springframework.jdbc.core.simple;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.jdbc.core.metadata.CallMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlInOutParameter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Types;
......@@ -16,74 +13,51 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.SqlInOutParameter;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.metadata.CallMetaDataContext;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
/**
* Mock object based tests for CallMetaDataContext.
*
* @author Thomas Risberg
*/
public class CallMetaDataContextTests extends TestCase {
private MockControl ctrlDataSource;
private DataSource mockDataSource;
private MockControl ctrlConnection;
private Connection mockConnection;
private MockControl ctrlDatabaseMetaData;
private DatabaseMetaData mockDatabaseMetaData;
private CallMetaDataContext context = new CallMetaDataContext();
@Override
protected void setUp() throws Exception {
super.setUp();
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
ctrlConnection = MockControl.createControl(Connection.class);
mockConnection = (Connection) ctrlConnection.getMock();
mockConnection.getMetaData();
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
mockConnection.close();
ctrlConnection.setDefaultVoidCallable();
public class CallMetaDataContextTests {
ctrlDataSource = MockControl.createControl(DataSource.class);
mockDataSource = (DataSource) ctrlDataSource.getMock();
mockDataSource.getConnection();
ctrlDataSource.setDefaultReturnValue(mockConnection);
private DataSource dataSource;
private Connection connection;
private DatabaseMetaData databaseMetaData;
}
private CallMetaDataContext context = new CallMetaDataContext();
@Override
protected void tearDown() throws Exception {
super.tearDown();
ctrlDatabaseMetaData.verify();
ctrlDataSource.verify();
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
databaseMetaData = mock(DatabaseMetaData.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
dataSource = mock(DataSource.class);
given(dataSource.getConnection()).willReturn(connection);
}
protected void replay() {
ctrlDatabaseMetaData.replay();
ctrlConnection.replay();
ctrlDataSource.replay();
@After
public void verifyClosed() throws Exception {
verify(connection).close();
}
@Test
public void testMatchParameterValuesAndSqlInOutParameters() throws Exception {
final String TABLE = "customers";
final String USER = "me";
mockDatabaseMetaData.getDatabaseProductName();
ctrlDatabaseMetaData.setReturnValue("MyDB");
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.getUserName();
ctrlDatabaseMetaData.setReturnValue(USER);
mockDatabaseMetaData.storesUpperCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(false);
mockDatabaseMetaData.storesLowerCaseIdentifiers();
ctrlDatabaseMetaData.setReturnValue(true);
replay();
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
given(databaseMetaData.getUserName()).willReturn(USER);
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
List<SqlParameter> parameters = new ArrayList<SqlParameter>();
parameters.add(new SqlParameter("id", Types.NUMERIC));
......@@ -96,7 +70,7 @@ public class CallMetaDataContextTests extends TestCase {
parameterSource.addValue("customer_no", "12345XYZ");
context.setProcedureName(TABLE);
context.initializeMetaData(mockDataSource);
context.initializeMetaData(dataSource);
context.processParameters(parameters);
Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource);
......@@ -110,7 +84,6 @@ public class CallMetaDataContextTests extends TestCase {
List<SqlParameter> callParameters = context.getCallParameters();
assertEquals("Wrong number of call parameters", 3, callParameters.size());
}
}
......@@ -16,26 +16,27 @@
package org.springframework.jdbc.core.support;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @author Juergen Hoeller
* @since 30.07.2003
*/
public class JdbcDaoSupportTests extends TestCase {
public class JdbcDaoSupportTests {
@Test
public void testJdbcDaoSupportWithDataSource() throws Exception {
MockControl dsControl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) dsControl.getMock();
final List test = new ArrayList();
DataSource ds = mock(DataSource.class);
final List<String> test = new ArrayList<String>();
JdbcDaoSupport dao = new JdbcDaoSupport() {
@Override
protected void initDao() {
......@@ -49,9 +50,10 @@ public class JdbcDaoSupportTests extends TestCase {
assertEquals("initDao called", test.size(), 1);
}
@Test
public void testJdbcDaoSupportWithJdbcTemplate() throws Exception {
JdbcTemplate template = new JdbcTemplate();
final List test = new ArrayList();
final List<String> test = new ArrayList<String>();
JdbcDaoSupport dao = new JdbcDaoSupport() {
@Override
protected void initDao() {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册