Merge branch 'SPR-10126' into cleanup-3.2.x
* SPR-10126: Replace EasyMock with Mockito in test sources
This commit is contained in:
14
build.gradle
14
build.gradle
@@ -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);
|
||||
MethodInvocation methodInvocation = mock(MethodInvocation.class);
|
||||
|
||||
Method toString = String.class.getMethod("toString", new Class[0]);
|
||||
Object[] arguments = new Object[]{"$ One \\$", new Long(2)};
|
||||
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!");
|
||||
|
||||
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));
|
||||
|
||||
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);
|
||||
MethodInvocation mi = mock(MethodInvocation.class);
|
||||
given(mi.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
|
||||
|
||||
Method toString = String.class.getMethod("toString", new Class[0]);
|
||||
|
||||
expect(mi.getMethod()).andReturn(toString);
|
||||
expect(mi.proceed()).andReturn(null);
|
||||
log.trace(isA(String.class));
|
||||
|
||||
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);
|
||||
MethodInvocation mi = mock(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));
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
// 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 {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* 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);
|
||||
standardContentHandler = mockContentHandler();
|
||||
standardReader.setContentHandler(standardContentHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
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()));
|
||||
|
||||
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());
|
||||
|
||||
verifyIdenticalInvocations(standardContentHandler, contentHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
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()));
|
||||
|
||||
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());
|
||||
|
||||
verifyIdenticalInvocations(standardContentHandler, contentHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
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()));
|
||||
|
||||
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());
|
||||
|
||||
verifyIdenticalInvocations(standardContentHandler, contentHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
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", expectedLexicalHandler);
|
||||
standardReader.parse(new InputSource(testLexicalHandlerXml.getInputStream()));
|
||||
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", actualLexicalHandler);
|
||||
staxXmlReader.parse(new InputSource());
|
||||
|
||||
verifyIdenticalInvocations(expectedLexicalHandler, actualLexicalHandler);
|
||||
}
|
||||
|
||||
private final LexicalHandler mockLexicalHandler() throws Exception {
|
||||
LexicalHandler lexicalHandler = mock(LexicalHandler.class);
|
||||
willAnswer(new CopyCharsAnswer()).given(lexicalHandler).comment(any(char[].class), anyInt(), anyInt());
|
||||
return lexicalHandler;
|
||||
}
|
||||
|
||||
private InputStream createTestInputStream() {
|
||||
return getClass().getResourceAsStream("testContentHandler.xml");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contentHandlerNamespacesNoPrefixes() throws SAXException, IOException, XMLStreamException {
|
||||
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());
|
||||
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();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contentHandlerNamespacesPrefixes() throws SAXException, IOException, XMLStreamException {
|
||||
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());
|
||||
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();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contentHandlerNoNamespacesPrefixes() throws SAXException, IOException, XMLStreamException {
|
||||
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());
|
||||
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();
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
Resource testLexicalHandlerXml = new ClassPathResource("testLexicalHandler.xml", getClass());
|
||||
|
||||
standardReader.setContentHandler(null);
|
||||
standardReader.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
|
||||
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);
|
||||
|
||||
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(testLexicalHandlerXml.getInputStream());
|
||||
|
||||
staxXmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
|
||||
staxXmlReader.parse(new InputSource());
|
||||
lexicalHandlerControl.verify();
|
||||
}
|
||||
|
||||
protected abstract AbstractStaxXMLReader createStaxXmlReader(InputStream inputStream) throws XMLStreamException;
|
||||
|
||||
/** Easymock {@code AbstractMatcher} implementation that matches SAX arguments. */
|
||||
@SuppressWarnings("serial")
|
||||
protected static class SaxArgumentMatcher extends AbstractMatcher {
|
||||
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;
|
||||
}
|
||||
}).given(contentHandler).startElement(anyString(), anyString(), anyString(), any(Attributes.class));
|
||||
return contentHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(Object[] expected, Object[] actual) {
|
||||
if (expected == actual) {
|
||||
return true;
|
||||
protected <T> void verifyIdenticalInvocations(T expected, T actual) {
|
||||
MockitoUtils.verifySameInvocations(expected, actual,
|
||||
new SkipLocatorArgumentsAdapter(), new CharArrayToStringAdapter(), new PartialAttributesAdapter());
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
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);
|
||||
return arguments;
|
||||
}
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private static class PartialAttributes {
|
||||
|
||||
private Attributes attributes;
|
||||
|
||||
public PartialAttributes(Attributes attributes) {
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean argumentMatches(Object expected, Object actual) {
|
||||
if (expected instanceof char[]) {
|
||||
return Arrays.equals((char[]) expected, (char[]) actual);
|
||||
}
|
||||
else if (expected instanceof Attributes) {
|
||||
Attributes expectedAttributes = (Attributes) expected;
|
||||
Attributes actualAttributes = (Attributes) actual;
|
||||
if (expectedAttributes.getLength() != actualAttributes.getLength()) {
|
||||
public int hashCode() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
@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(", ");
|
||||
}
|
||||
}
|
||||
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 true;
|
||||
}
|
||||
}
|
||||
|
||||
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 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);
|
||||
}
|
||||
|
||||
public void endDTD() throws SAXException {
|
||||
wrappee.endDTD();
|
||||
}
|
||||
|
||||
public void startEntity(String name) throws SAXException {
|
||||
wrappee.startEntity(name);
|
||||
}
|
||||
|
||||
public void endEntity(String name) throws SAXException {
|
||||
wrappee.endEntity(name);
|
||||
}
|
||||
|
||||
public void startCDATA() throws SAXException {
|
||||
wrappee.startCDATA();
|
||||
}
|
||||
|
||||
public void endCDATA() throws SAXException {
|
||||
wrappee.endCDATA();
|
||||
}
|
||||
|
||||
public void comment(char ch[], int start, int length) throws SAXException {
|
||||
wrappee.comment(copy(ch), start, length);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* 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 {
|
||||
public abstract class AbstractRowMapperTests {
|
||||
|
||||
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);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(Person.class));
|
||||
assertEquals(1, result.size());
|
||||
Person bean = (Person) result.get(0);
|
||||
verifyPerson(bean);
|
||||
@Test
|
||||
public void testOverridingSameClassDefinedForMapping() {
|
||||
BeanPropertyRowMapper<Person> mapper = new BeanPropertyRowMapper<Person>(Person.class);
|
||||
mapper.setMappedClass(Person.class);
|
||||
}
|
||||
|
||||
public void testMappingWithInheritance() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(ConcretePerson.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());
|
||||
ConcretePerson bean = (ConcretePerson) result.get(0);
|
||||
verifyPerson(result.get(0));
|
||||
mock.verifyClosed();
|
||||
}
|
||||
|
||||
@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());
|
||||
verifyConcretePerson(result.get(0));
|
||||
mock.verifyClosed();
|
||||
}
|
||||
|
||||
@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());
|
||||
verifyConcretePerson(result.get(0));
|
||||
mock.verifyClosed();
|
||||
}
|
||||
|
||||
@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 = result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
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 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));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@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());
|
||||
ConcretePerson bean = (ConcretePerson) result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
verifySpacePerson(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));
|
||||
assertEquals(1, result.size());
|
||||
ExtendedPerson bean = (ExtendedPerson) result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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));
|
||||
assertEquals(1, result.size());
|
||||
SpacePerson bean = (SpacePerson) result.get(0);
|
||||
verifySpacePerson(bean);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,11 @@
|
||||
|
||||
package org.springframework.jdbc.core;
|
||||
|
||||
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.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
@@ -25,9 +30,10 @@ import java.sql.Types;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
|
||||
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
|
||||
@@ -38,213 +44,104 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
|
||||
*/
|
||||
public class RowMapperTests extends TestCase {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
private Connection connection;
|
||||
private Statement statement;
|
||||
private PreparedStatement preparedStatement;
|
||||
private ResultSet resultSet;
|
||||
|
||||
private MockControl conControl;
|
||||
private Connection con;
|
||||
private MockControl rsControl;
|
||||
private ResultSet rs;
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private List result;
|
||||
private JdbcTemplate template;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws SQLException {
|
||||
conControl = MockControl.createControl(Connection.class);
|
||||
con = (Connection) conControl.getMock();
|
||||
con.isClosed();
|
||||
conControl.setDefaultReturnValue(false);
|
||||
private List<TestBean> result;
|
||||
|
||||
rsControl = MockControl.createControl(ResultSet.class);
|
||||
rs = (ResultSet) rsControl.getMock();
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 1);
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue("tb1", 1);
|
||||
rs.getInt(2);
|
||||
rsControl.setReturnValue(1, 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 1);
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue("tb2", 1);
|
||||
rs.getInt(2);
|
||||
rsControl.setReturnValue(2, 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(false, 1);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(1);
|
||||
rsControl.replay();
|
||||
|
||||
jdbcTemplate = new JdbcTemplate();
|
||||
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
|
||||
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
jdbcTemplate.afterPropertiesSet();
|
||||
@Before
|
||||
public void setUp() throws SQLException {
|
||||
connection = mock(Connection.class);
|
||||
statement = mock(Statement.class);
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
resultSet = mock(ResultSet.class);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
|
||||
given(statement.executeQuery(anyString())).willReturn(resultSet);
|
||||
given(preparedStatement.executeQuery()).willReturn(resultSet);
|
||||
given(resultSet.next()).willReturn(true, true, false);
|
||||
given(resultSet.getString(1)).willReturn("tb1", "tb2");
|
||||
given(resultSet.getInt(2)).willReturn(1, 2);
|
||||
template = new JdbcTemplate();
|
||||
template.setDataSource(new SingleConnectionDataSource(connection, false));
|
||||
template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
template.afterPropertiesSet();
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 1);
|
||||
stmt.executeQuery("some SQL");
|
||||
stmtControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
stmt.getWarnings();
|
||||
stmtControl.setReturnValue(null, 1);
|
||||
}
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
|
||||
result = jdbcTemplate.query("some SQL", new TestRowMapper());
|
||||
|
||||
stmtControl.verify();
|
||||
verify();
|
||||
@After
|
||||
public void verifyClosed() throws Exception {
|
||||
verify(resultSet).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
public void testPreparedStatementCreatorWithRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
new PreparedStatementCreator() {
|
||||
@Override
|
||||
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
||||
return ps;
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testPreparedStatementSetterWithRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new PreparedStatementSetter() {
|
||||
@Override
|
||||
public void setValues(PreparedStatement ps) throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testQueryWithArgsAndRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test1");
|
||||
ps.setString(2, "test2");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new Object[] {"test1", "test2"},
|
||||
new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test1");
|
||||
ps.setString(2, "test2");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new Object[] {"test1", "test2"},
|
||||
new int[] {Types.VARCHAR, Types.VARCHAR},
|
||||
new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
protected void verify() {
|
||||
conControl.verify();
|
||||
rsControl.verify();
|
||||
|
||||
@After
|
||||
public void verifyResults() {
|
||||
assertTrue(result != null);
|
||||
assertEquals(2, result.size());
|
||||
TestBean tb1 = (TestBean) result.get(0);
|
||||
TestBean tb2 = (TestBean) result.get(1);
|
||||
assertEquals("tb1", tb1.getName());
|
||||
assertEquals(1, tb1.getAge());
|
||||
assertEquals("tb2", tb2.getName());
|
||||
assertEquals(2, tb2.getAge());
|
||||
assertEquals("tb1", result.get(0).getName());
|
||||
assertEquals("tb2", result.get(1).getName());
|
||||
assertEquals(1, result.get(0).getAge());
|
||||
assertEquals(2, result.get(1).getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
result = template.query("some SQL", new TestRowMapper());
|
||||
verify(statement).close();
|
||||
}
|
||||
|
||||
private static class TestRowMapper implements RowMapper {
|
||||
@Test
|
||||
public void testPreparedStatementCreatorWithRowMapper() throws SQLException {
|
||||
result = template.query(new PreparedStatementCreator() {
|
||||
@Override
|
||||
public PreparedStatement createPreparedStatement(Connection con)
|
||||
throws SQLException {
|
||||
return preparedStatement;
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPreparedStatementSetterWithRowMapper() throws SQLException {
|
||||
result = template.query("some SQL", new PreparedStatementSetter() {
|
||||
@Override
|
||||
public void setValues(PreparedStatement ps) throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
verify(preparedStatement).setString(1, "test");
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryWithArgsAndRowMapper() throws SQLException {
|
||||
result = template.query("some SQL",
|
||||
new Object[] { "test1", "test2" },
|
||||
new TestRowMapper());
|
||||
preparedStatement.setString(1, "test1");
|
||||
preparedStatement.setString(2, "test2");
|
||||
preparedStatement.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException {
|
||||
result = template.query("some SQL",
|
||||
new Object[] { "test1", "test2" },
|
||||
new int[] { Types.VARCHAR, Types.VARCHAR },
|
||||
new TestRowMapper());
|
||||
verify(preparedStatement).setString(1, "test1");
|
||||
verify(preparedStatement).setString(2, "test2");
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
private static class TestRowMapper implements RowMapper<TestBean> {
|
||||
@Override
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
public TestBean mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new TestBean(rs.getString(1), rs.getInt(2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
|
||||
package org.springframework.jdbc.core;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
@@ -23,203 +27,156 @@ import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 31.08.2004
|
||||
*/
|
||||
public class StatementCreatorUtilsTests extends TestCase {
|
||||
public class StatementCreatorUtilsTests {
|
||||
|
||||
private MockControl psControl;
|
||||
private PreparedStatement ps;
|
||||
private PreparedStatement preparedStatement;
|
||||
|
||||
@Override
|
||||
protected void setUp() {
|
||||
psControl = MockControl.createControl(PreparedStatement.class);
|
||||
ps = (PreparedStatement) psControl.getMock();
|
||||
@Before
|
||||
public void setUp() {
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() {
|
||||
psControl.verify();
|
||||
@Test public void testSetParameterValueWithNullAndType() throws SQLException {
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, null);
|
||||
verify(preparedStatement).setNull(1, Types.VARCHAR);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndType() throws SQLException {
|
||||
ps.setNull(1, Types.VARCHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, null);
|
||||
@Test public void testSetParameterValueWithNullAndTypeName() throws SQLException {
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, "mytype", null);
|
||||
verify(preparedStatement).setNull(1, Types.VARCHAR, "mytype");
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndTypeName() throws SQLException {
|
||||
ps.setNull(1, Types.VARCHAR, "mytype");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, "mytype", null);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndUnknownType() throws SQLException {
|
||||
ps.setNull(1, Types.NULL);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
@Test public void testSetParameterValueWithNullAndUnknownType() throws SQLException {
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
verify(preparedStatement).setNull(1, Types.NULL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithNullAndUnknownTypeOnInformix() throws SQLException {
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
|
||||
ps.getConnection();
|
||||
psControl.setReturnValue(con, 1);
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(metaData, 1);
|
||||
metaData.getDatabaseProductName();
|
||||
metaDataControl.setReturnValue("Informix Dynamic Server");
|
||||
metaData.getDriverName();
|
||||
metaDataControl.setReturnValue("Informix Driver");
|
||||
ps.setObject(1, null);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
conControl.replay();
|
||||
metaDataControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
conControl.verify();
|
||||
metaDataControl.verify();
|
||||
Connection con = mock(Connection.class);
|
||||
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
|
||||
given(preparedStatement.getConnection()).willReturn(con);
|
||||
given(con.getMetaData()).willReturn(metaData);
|
||||
given(metaData.getDatabaseProductName()).willReturn("Informix Dynamic Server");
|
||||
given(metaData.getDriverName()).willReturn("Informix Driver");
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
verify(metaData).getDatabaseProductName();
|
||||
verify(metaData).getDriverName();
|
||||
verify(preparedStatement).setObject(1, null);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
|
||||
ps.getConnection();
|
||||
psControl.setReturnValue(con, 1);
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(metaData, 1);
|
||||
metaData.getDatabaseProductName();
|
||||
metaDataControl.setReturnValue("Apache Derby");
|
||||
metaData.getDriverName();
|
||||
metaDataControl.setReturnValue("Apache Derby Embedded Driver");
|
||||
ps.setNull(1, Types.VARCHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
conControl.replay();
|
||||
metaDataControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
conControl.verify();
|
||||
metaDataControl.verify();
|
||||
@Test public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
|
||||
Connection con = mock(Connection.class);
|
||||
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
|
||||
given(preparedStatement.getConnection()).willReturn(con);
|
||||
given(con.getMetaData()).willReturn(metaData);
|
||||
given(metaData.getDatabaseProductName()).willReturn("Apache Derby");
|
||||
given(metaData.getDriverName()).willReturn("Apache Derby Embedded Driver");
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
verify(metaData).getDatabaseProductName();
|
||||
verify(metaData).getDriverName();
|
||||
verify(preparedStatement).setNull(1, Types.VARCHAR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithString() throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, "test");
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.VARCHAR, null, "test");
|
||||
verify(preparedStatement).setString(1, "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithStringAndSpecialType() throws SQLException {
|
||||
ps.setObject(1, "test", Types.CHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.CHAR, null, "test");
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.CHAR, null, "test");
|
||||
verify(preparedStatement).setObject(1, "test", Types.CHAR);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithStringAndUnknownType() throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, "test");
|
||||
@Test public void testSetParameterValueWithStringAndUnknownType() throws SQLException {
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, "test");
|
||||
verify(preparedStatement).setString(1, "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithSqlDate() throws SQLException {
|
||||
java.sql.Date date = new java.sql.Date(1000);
|
||||
ps.setDate(1, date);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
|
||||
verify(preparedStatement).setDate(1, date);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithDateAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setDate(1, new java.sql.Date(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date);
|
||||
verify(preparedStatement).setDate(1, new java.sql.Date(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithDateAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, cal);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, cal);
|
||||
verify(preparedStatement).setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithSqlTime() throws SQLException {
|
||||
java.sql.Time time = new java.sql.Time(1000);
|
||||
ps.setTime(1, time);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, time);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, time);
|
||||
verify(preparedStatement).setTime(1, time);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithTimeAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTime(1, new java.sql.Time(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, date);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, date);
|
||||
verify(preparedStatement).setTime(1, new java.sql.Time(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithTimeAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, cal);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIME, null, cal);
|
||||
verify(preparedStatement).setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithSqlTimestamp() throws SQLException {
|
||||
java.sql.Timestamp timestamp = new java.sql.Timestamp(1000);
|
||||
ps.setTimestamp(1, timestamp);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, timestamp);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, timestamp);
|
||||
verify(preparedStatement).setTimestamp(1, timestamp);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithTimestampAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, date);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, date);
|
||||
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithTimestampAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, cal);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.TIMESTAMP, null, cal);
|
||||
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithDateAndUnknownType() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
|
||||
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetParameterValueWithCalendarAndUnknownType() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, cal);
|
||||
StatementCreatorUtils.setParameterValue(preparedStatement, 1, SqlTypeValue.TYPE_UNKNOWN, null, cal);
|
||||
verify(preparedStatement).setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,41 +16,49 @@
|
||||
|
||||
package org.springframework.jdbc.core.namedparam;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
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.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.Customer;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.PreparedStatementCallback;
|
||||
import org.springframework.jdbc.core.ResultSetExtractor;
|
||||
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.BatchUpdateTestHelper;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
|
||||
public class NamedParameterJdbcTemplateTests {
|
||||
|
||||
private static final String SELECT_NAMED_PARAMETERS =
|
||||
"select id, forename from custmr where id = :id and country = :country";
|
||||
@@ -64,255 +72,166 @@ public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
|
||||
|
||||
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private Connection connection;
|
||||
private DataSource dataSource;
|
||||
private PreparedStatement preparedStatement;
|
||||
private ResultSet resultSet;
|
||||
private DatabaseMetaData databaseMetaData;
|
||||
private Map<String, Object> params = new HashMap<String, Object>();
|
||||
private NamedParameterJdbcTemplate namedParameterTemplate;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = mock(Connection.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
resultSet = mock(ResultSet.class);
|
||||
namedParameterTemplate = new NamedParameterJdbcTemplate(dataSource);
|
||||
databaseMetaData = mock(DatabaseMetaData.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
|
||||
given(preparedStatement.getConnection()).willReturn(connection);
|
||||
given(preparedStatement.executeQuery()).willReturn(resultSet);
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MySQL");
|
||||
given(databaseMetaData.supportsBatchUpdates()).willReturn(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlResultSet.replay();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testNullDataSourceProvidedToCtor() throws Exception {
|
||||
try {
|
||||
new NamedParameterJdbcTemplate((DataSource) null);
|
||||
fail("should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException ex) { /* expected */ }
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
new NamedParameterJdbcTemplate((DataSource) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullJdbcTemplateProvidedToCtor() throws Exception {
|
||||
try {
|
||||
new NamedParameterJdbcTemplate((JdbcOperations) null);
|
||||
fail("should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException ex) { /* expected */ }
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
new NamedParameterJdbcTemplate((JdbcOperations) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecute() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
params.put("perfId", 1);
|
||||
params.put("priceId", 1);
|
||||
Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
|
||||
new PreparedStatementCallback<Object>() {
|
||||
@Override
|
||||
public Object doInPreparedStatement(PreparedStatement ps)
|
||||
throws SQLException {
|
||||
assertEquals(preparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(1));
|
||||
params.put("priceId", new Integer(1));
|
||||
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
|
||||
@Override
|
||||
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
|
||||
assertEquals(mockPreparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
}));
|
||||
assertEquals("result", result);
|
||||
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1);
|
||||
verify(preparedStatement).setObject(2, 1);
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecuteWithTypedParameters() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
|
||||
Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
|
||||
new PreparedStatementCallback<Object>() {
|
||||
@Override
|
||||
public Object doInPreparedStatement(PreparedStatement ps)
|
||||
throws SQLException {
|
||||
assertEquals(preparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
|
||||
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
|
||||
@Override
|
||||
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
|
||||
assertEquals(mockPreparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
}));
|
||||
assertEquals("result", result);
|
||||
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setObject(2, 1, Types.INTEGER);
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
public void testUpdate() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
@Test public void testUpdate() throws SQLException {
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
params.put("perfId", 1);
|
||||
params.put("priceId", 1);
|
||||
int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(1));
|
||||
params.put("priceId", new Integer(1));
|
||||
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1);
|
||||
verify(preparedStatement).setObject(2, 1);
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateWithTypedParameters() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
|
||||
int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
|
||||
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setObject(2, 1, Types.INTEGER);
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryWithResultSetExtractor() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getInt("id")).willReturn(1);
|
||||
given(resultSet.getString("forename")).willReturn("rod");
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("country", "UK");
|
||||
Customer cust = (Customer) jt.query(SELECT_NAMED_PARAMETERS, params, new ResultSetExtractor() {
|
||||
@Override
|
||||
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
|
||||
rs.next();
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
Customer cust = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
|
||||
new ResultSetExtractor<Customer>() {
|
||||
@Override
|
||||
public Customer extractData(ResultSet rs) throws SQLException,
|
||||
DataAccessException {
|
||||
rs.next();
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setString(2, "UK");
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryWithRowCallbackHandler() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt("id")).willReturn(1);
|
||||
given(resultSet.getString("forename")).willReturn("rod");
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("country", "UK");
|
||||
final List customers = new LinkedList();
|
||||
jt.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
|
||||
final List<Customer> customers = new LinkedList<Customer>();
|
||||
namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
|
||||
@Override
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
@@ -321,218 +240,148 @@ public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
|
||||
customers.add(cust);
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(1, customers.size());
|
||||
Customer cust = (Customer) customers.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
|
||||
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setString(2, "UK");
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryWithRowMapper() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt("id")).willReturn(1);
|
||||
given(resultSet.getString("forename")).willReturn("rod");
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("country", "UK");
|
||||
List customers = jt.query(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
|
||||
@Override
|
||||
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
List<Customer> customers = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
|
||||
new RowMapper<Customer>() {
|
||||
@Override
|
||||
public Customer mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
assertEquals(1, customers.size());
|
||||
Customer cust = (Customer) customers.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
|
||||
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setString(2, "UK");
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithRowMapper() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt("id")).willReturn(1);
|
||||
given(resultSet.getString("forename")).willReturn("rod");
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
|
||||
params.put("country", "UK");
|
||||
Customer cust = (Customer) jt.queryForObject(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
|
||||
@Override
|
||||
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
Customer cust = namedParameterTemplate.queryForObject(SELECT_NAMED_PARAMETERS, params,
|
||||
new RowMapper<Customer>() {
|
||||
@Override
|
||||
public Customer mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
|
||||
verify(preparedStatement).setString(2, "UK");
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithPlainMap() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final Map[] ids = new Map[2];
|
||||
@SuppressWarnings("unchecked")
|
||||
final Map<String, Integer>[] ids = new Map[2];
|
||||
ids[0] = Collections.singletonMap("id", 100);
|
||||
ids[1] = Collections.singletonMap("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource, false);
|
||||
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
|
||||
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 100);
|
||||
verify(preparedStatement).setObject(1, 200);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement, atLeastOnce()).close();
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithSqlParameterSource() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource("id", 100);
|
||||
ids[1] = new MapSqlParameterSource("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource, false);
|
||||
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
|
||||
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 100);
|
||||
verify(preparedStatement).setObject(1, 200);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement, atLeastOnce()).close();
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource().addValue("id", 100, Types.NUMERIC);
|
||||
ids[1] = new MapSqlParameterSource().addValue("id", 200, Types.NUMERIC);
|
||||
final int[] sqlTypes = new int[] {Types.NUMERIC};
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource, false);
|
||||
namedParameterTemplate = new NamedParameterJdbcTemplate(template);
|
||||
int[] actualRowsAffected = namedParameterTemplate.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 100, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(1, 200, Types.NUMERIC);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement, atLeastOnce()).close();
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,6 +16,14 @@
|
||||
|
||||
package org.springframework.jdbc.core.namedparam;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
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.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
@@ -27,576 +35,261 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class NamedParameterQueryTests extends AbstractJdbcTests {
|
||||
public class NamedParameterQueryTests {
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private MockControl ctrlResultSetMetaData;
|
||||
private ResultSetMetaData mockResultSetMetaData;
|
||||
private DataSource dataSource;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
|
||||
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
|
||||
private Connection connection;
|
||||
|
||||
private PreparedStatement preparedStatement;
|
||||
|
||||
private ResultSet resultSet;
|
||||
|
||||
private ResultSetMetaData resultSetMetaData;
|
||||
|
||||
private NamedParameterJdbcTemplate template;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = mock(Connection.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
resultSet = mock(ResultSet.class);
|
||||
resultSetMetaData = mock(ResultSetMetaData.class);
|
||||
template = new NamedParameterJdbcTemplate(dataSource);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(resultSetMetaData.getColumnCount()).willReturn(1);
|
||||
given(resultSetMetaData.getColumnLabel(1)).willReturn("age");
|
||||
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
|
||||
given(preparedStatement.executeQuery()).willReturn(resultSet);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlResultSet.replay();
|
||||
ctrlResultSetMetaData.replay();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (false && shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlResultSet.verify();
|
||||
ctrlResultSetMetaData.verify();
|
||||
}
|
||||
@After
|
||||
public void verifyClose() throws Exception {
|
||||
verify(preparedStatement).close();
|
||||
verify(resultSet).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithParamMap() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1, 2);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 2);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData, 2);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(12));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, true, false);
|
||||
given(resultSet.getObject(1)).willReturn(11, 12);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
List<Map<String, Object>> li = template.queryForList(
|
||||
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 2, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
assertEquals("Second row is Integer", 12, ((Integer)((Map)li.get(1)).get("age")).intValue());
|
||||
assertEquals("First row is Integer", 11,
|
||||
((Integer) ((Map) li.get(0)).get("age")).intValue());
|
||||
assertEquals("Second row is Integer", 12,
|
||||
((Integer) ((Map) li.get(1)).get("age")).intValue());
|
||||
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithParamMapAndEmptyResult() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.next()).willReturn(false);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
List<Map<String, Object>> li = template.queryForList(
|
||||
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 0, li.size());
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithParamMapAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getObject(1)).willReturn(11);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
List<Map<String, Object>> li = template.queryForList(
|
||||
"SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
assertEquals("First row is Integer", 11,
|
||||
((Integer) ((Map) li.get(0)).get("age")).intValue());
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(11);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
@Test
|
||||
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn()
|
||||
throws Exception {
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(11);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
List<Integer> li = template.queryForList("SELECT AGE FROM CUSTMR WHERE ID < :id",
|
||||
parms, Integer.class);
|
||||
|
||||
List li = template.queryForList(sql, parms, Integer.class);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer) li.get(0)).intValue());
|
||||
assertEquals("First row is Integer", 11, li.get(0).intValue());
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForMapWithParamMapAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getObject(1)).willReturn(11);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
Map map = template.queryForMap("SELECT AGE FROM CUSTMR WHERE ID < :id", parms);
|
||||
|
||||
Map map = template.queryForMap(sql, parms);
|
||||
assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue());
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithParamMapAndRowMapper() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
|
||||
parms, new RowMapper<Object>() {
|
||||
@Override
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return rs.getInt(1);
|
||||
}
|
||||
});
|
||||
|
||||
Object o = template.queryForObject(sql, parms, new RowMapper() {
|
||||
@Override
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new Integer(rs.getInt(1));
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithMapAndInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
Map<String, Object> parms = new HashMap<String, Object>();
|
||||
parms.put("id", 3);
|
||||
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
|
||||
parms, Integer.class);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
Map parms = new HashMap();
|
||||
parms.put("id", new Integer(3));
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithParamMapAndInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
|
||||
parms, Integer.class);
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithParamMapAndList() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID IN (:ids)";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID IN (?, ?)";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(4));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("ids", Arrays.asList(new Object[] {new Integer(3), new Integer(4)}));
|
||||
|
||||
parms.addValue("ids", Arrays.asList(new Object[] { 3, 4 }));
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
verify(connection).prepareStatement(sqlToUse);
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithParamMapAndListOfExpressionLists() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "Rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(3, new Integer(4));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(4, "Juergen");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
List l1 = new ArrayList();
|
||||
l1.add(new Object[] {new Integer(3), "Rod"});
|
||||
l1.add(new Object[] {new Integer(4), "Juergen"});
|
||||
List<Object[]> l1 = new ArrayList<Object[]>();
|
||||
l1.add(new Object[] { 3, "Rod" });
|
||||
l1.add(new Object[] { 4, "Juergen" });
|
||||
parms.addValue("multiExpressionList", l1);
|
||||
Object o = template.queryForObject(
|
||||
"SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)",
|
||||
parms, Integer.class);
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
verify(connection).prepareStatement(
|
||||
"SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForIntWithParamMap() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22.0d);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getInt(1)).willReturn(22);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
parms.addValue("id", 3);
|
||||
int i = template.queryForInt("SELECT AGE FROM CUSTMR WHERE ID = :id", parms);
|
||||
|
||||
int i = template.queryForInt(sql, parms);
|
||||
assertEquals("Return of an int", 22, i);
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForLongWithParamBean() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getLong(1)).willReturn(87L);
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
BeanPropertySqlParameterSource parms = new BeanPropertySqlParameterSource(
|
||||
new ParameterBean(3));
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getLong(1);
|
||||
ctrlResultSet.setReturnValue(87.0d);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
long l = template.queryForLong("SELECT AGE FROM CUSTMR WHERE ID = :id", parms);
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
BeanPropertySqlParameterSource parms = new BeanPropertySqlParameterSource(new ParameterBean(3));
|
||||
|
||||
long l = template.queryForLong(sql, parms);
|
||||
assertEquals("Return of a long", 87, l);
|
||||
verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
|
||||
verify(preparedStatement).setObject(1, 3, Types.INTEGER);
|
||||
}
|
||||
|
||||
|
||||
private static class ParameterBean {
|
||||
static class ParameterBean {
|
||||
|
||||
private int id;
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
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;
|
||||
public class CallMetaDataContextTests {
|
||||
|
||||
private DataSource dataSource;
|
||||
private Connection connection;
|
||||
private DatabaseMetaData databaseMetaData;
|
||||
|
||||
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();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
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,9 +16,13 @@
|
||||
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
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.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.jdbc.core.AbstractRowMapperTests;
|
||||
import org.springframework.jdbc.core.test.ConcretePerson;
|
||||
@@ -29,46 +33,43 @@ import org.springframework.jdbc.core.test.Person;
|
||||
*/
|
||||
public class ParameterizedBeanPropertyRowMapperTests extends AbstractRowMapperTests {
|
||||
|
||||
private SimpleJdbcTemplate simpleJdbcTemplate;
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Override
|
||||
protected void setUp() throws SQLException {
|
||||
super.setUp();
|
||||
simpleJdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void testOverridingDifferentClassDefinedForMapping() {
|
||||
ParameterizedBeanPropertyRowMapper mapper = ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
|
||||
thrown.expect(InvalidDataAccessApiUsageException.class);
|
||||
mapper.setMappedClass(Long.class);
|
||||
}
|
||||
|
||||
public void testOverridingClassDefinedForMapping() {
|
||||
ParameterizedBeanPropertyRowMapper<Person> mapper =
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
|
||||
try {
|
||||
((ParameterizedBeanPropertyRowMapper) mapper).setMappedClass(Long.class);
|
||||
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
mapper.setMappedClass(Person.class);
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
@Test
|
||||
public void testOverridingSameClassDefinedForMapping() {
|
||||
ParameterizedBeanPropertyRowMapper<Person> mapper = ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
|
||||
mapper.setMappedClass(Person.class);
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
List<Person> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
@Test
|
||||
public void testStaticQueryWithRowMapper() throws Exception {
|
||||
Mock mock = new Mock();
|
||||
List<Person> result = mock.getJdbcTemplate().query(
|
||||
"select name, age, birth_date, balance from people",
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(Person.class));
|
||||
assertEquals(1, result.size());
|
||||
Person bean = result.get(0);
|
||||
verifyPerson(bean);
|
||||
verifyPerson(result.get(0));
|
||||
mock.verifyClosed();
|
||||
}
|
||||
|
||||
public void testMappingWithInheritance() throws SQLException {
|
||||
List<ConcretePerson> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
@Test
|
||||
public void testMappingWithInheritance() throws Exception {
|
||||
Mock mock = new Mock();
|
||||
List<ConcretePerson> result = mock.getJdbcTemplate().query(
|
||||
"select name, age, birth_date, balance from people",
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(ConcretePerson.class));
|
||||
assertEquals(1, result.size());
|
||||
ConcretePerson bean = result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
verifyConcretePerson(result.get(0));
|
||||
mock.verifyClosed();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,469 +16,274 @@
|
||||
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import static org.hamcrest.Matchers.sameInstance;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.build.test.hamcrest.Matchers.exceptionCause;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.core.SqlOutParameter;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* Mock object based tests for SimpleJdbcCall.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcCallTests extends TestCase {
|
||||
public class SimpleJdbcCallTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
private MockControl ctrlCallable;
|
||||
private CallableStatement mockCallable;
|
||||
private Connection connection;
|
||||
private DatabaseMetaData databaseMetaData;
|
||||
private DataSource dataSource;
|
||||
private CallableStatement callableStatement;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
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();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
ctrlCallable = MockControl.createControl(CallableStatement.class);
|
||||
mockCallable = (CallableStatement) ctrlCallable.getMock();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
ctrlCallable.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
ctrlCallable.replay();
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = mock(Connection.class);
|
||||
databaseMetaData = mock(DatabaseMetaData.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
callableStatement = mock(CallableStatement.class);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoSuchStoredProcedure() throws Exception {
|
||||
final String NO_SUCH_PROC = "x";
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("me");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
SQLException sex =
|
||||
new SQLException(
|
||||
"Syntax error or access violation exception",
|
||||
"42000");
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setThrowable(sex);
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
mockConnection.prepareCall(
|
||||
"{call " + NO_SUCH_PROC + "()}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(NO_SUCH_PROC);
|
||||
SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getUserName()).willReturn("me");
|
||||
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
|
||||
given(callableStatement.execute()).willThrow(sqlException);
|
||||
given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
|
||||
thrown.expect(BadSqlGrammarException.class);
|
||||
thrown.expect(exceptionCause(sameInstance(sqlException)));
|
||||
try {
|
||||
sproc.execute();
|
||||
fail("Shouldn't succeed in running stored procedure which doesn't exist");
|
||||
} catch (BadSqlGrammarException ex) {
|
||||
// OK
|
||||
}
|
||||
finally {
|
||||
verify(callableStatement).close();
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnnamedParameterHandling() throws Exception {
|
||||
final String MY_PROC = "my_proc";
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(MY_PROC);
|
||||
try {
|
||||
sproc.addDeclaredParameter(new SqlParameter(1));
|
||||
fail("Shouldn't succeed in adding unnamed parameter");
|
||||
} catch (InvalidDataAccessApiUsageException ex) {
|
||||
// OK
|
||||
}
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC);
|
||||
// Shouldn't succeed in adding unnamed parameter
|
||||
thrown.expect(InvalidDataAccessApiUsageException.class);
|
||||
sproc.addDeclaredParameter(new SqlParameter(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceProcWithoutMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(false);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER),
|
||||
new SqlOutParameter("newid", Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
new SqlOutParameter("newid",
|
||||
Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource().
|
||||
addValue("amount", 1103).
|
||||
addValue("custid", 3));
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithoutMetaData(false);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceProcWithoutMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(false);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER),
|
||||
new SqlOutParameter("newid", Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, amount, custid);
|
||||
new SqlOutParameter("newid",
|
||||
Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, 1103, 3);
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithoutMetaData(false);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceProcWithMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
initializeAddInvoiceWithMetaData(false);
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
|
||||
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
.addValue("amount", 1103)
|
||||
.addValue("custid", 3));
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
verifyAddInvoiceWithMetaData(false);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceProcWithMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
Number newId = adder.executeObject(Number.class, amount, custid);
|
||||
initializeAddInvoiceWithMetaData(false);
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
|
||||
Number newId = adder.executeObject(Number.class, 1103, 3);
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
verifyAddInvoiceWithMetaData(false);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceFuncWithoutMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(true);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(
|
||||
new SqlOutParameter("return", Types.INTEGER),
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER));
|
||||
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
.addValue("amount", 1103)
|
||||
.addValue("custid", 3));
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithoutMetaData(true);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceFuncWithoutMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(true);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(
|
||||
new SqlOutParameter("return", Types.INTEGER),
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER));
|
||||
Number newId = adder.executeFunction(Number.class, amount, custid);
|
||||
Number newId = adder.executeFunction(Number.class, 1103, 3);
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithoutMetaData(true);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoiceFuncWithMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
initializeAddInvoiceWithMetaData(true);
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
|
||||
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
.addValue("amount", 1103)
|
||||
.addValue("custid", 3));
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithMetaData(true);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
public void testAddInvoiceFuncWithMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
Number newId = adder.executeFunction(Number.class, amount, custid);
|
||||
@Test public void testAddInvoiceFuncWithMetaDataUsingArrayParams() throws Exception {
|
||||
initializeAddInvoiceWithMetaData(true);
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice");
|
||||
Number newId = adder.executeFunction(Number.class, 1103, 3);
|
||||
assertEquals(4, newId.intValue());
|
||||
verifyAddInvoiceWithMetaData(true);
|
||||
verify(connection, atLeastOnce()).close();
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
private void initializeAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException {
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("me");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
private void initializeAddInvoiceWithoutMetaData(boolean isFunction)
|
||||
throws SQLException {
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getUserName()).willReturn("me");
|
||||
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
|
||||
given(callableStatement.execute()).willReturn(false);
|
||||
given(callableStatement.getUpdateCount()).willReturn(-1);
|
||||
if (isFunction) {
|
||||
mockCallable.registerOutParameter(1, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(3, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
given(callableStatement.getObject(1)).willReturn(4L);
|
||||
given(connection.prepareCall("{? = call add_invoice(?, ?)}")
|
||||
).willReturn(callableStatement);
|
||||
}
|
||||
else {
|
||||
mockCallable.setObject(1, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.registerOutParameter(3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setReturnValue(false);
|
||||
mockCallable.getUpdateCount();
|
||||
ctrlCallable.setReturnValue(-1);
|
||||
if (isFunction) {
|
||||
mockCallable.getObject(1);
|
||||
}
|
||||
else {
|
||||
mockCallable.getObject(3);
|
||||
}
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
if (debugEnabled) {
|
||||
mockCallable.getWarnings();
|
||||
ctrlCallable.setReturnValue(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
if (isFunction) {
|
||||
mockConnection.prepareCall(
|
||||
"{? = call add_invoice(?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
else {
|
||||
mockConnection.prepareCall(
|
||||
"{call add_invoice(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
given(callableStatement.getObject(3)).willReturn(4L);
|
||||
given(connection.prepareCall("{call add_invoice(?, ?, ?)}")
|
||||
).willReturn(callableStatement);
|
||||
}
|
||||
}
|
||||
|
||||
private MockControl initializeAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getString("PROCEDURE_CAT");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getString("PROCEDURE_SCHEM");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getString("PROCEDURE_NAME");
|
||||
ctrlResultSet.setReturnValue("add_invoice");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
private void verifyAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException {
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(5);
|
||||
verify(callableStatement).registerOutParameter(1, 4);
|
||||
verify(callableStatement).setObject(2, 1103, 4);
|
||||
verify(callableStatement).setObject(3, 3, 4);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("amount");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
verify(callableStatement).setObject(1, 1103, 4);
|
||||
verify(callableStatement).setObject(2, 3, 4);
|
||||
verify(callableStatement).registerOutParameter(3, 4);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("amount");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("custid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("custid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("newid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("Oracle");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("ME");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
mockDatabaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
|
||||
if (isFunction) {
|
||||
mockCallable.registerOutParameter(1, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(3, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
else {
|
||||
mockCallable.setObject(1, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.registerOutParameter(3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setReturnValue(false);
|
||||
mockCallable.getUpdateCount();
|
||||
ctrlCallable.setReturnValue(-1);
|
||||
if (isFunction) {
|
||||
mockCallable.getObject(1);
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
}
|
||||
else {
|
||||
mockCallable.getObject(3);
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
}
|
||||
if (debugEnabled) {
|
||||
mockCallable.getWarnings();
|
||||
ctrlCallable.setReturnValue(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
if (isFunction) {
|
||||
mockConnection.prepareCall(
|
||||
"{? = call ADD_INVOICE(?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
else {
|
||||
mockConnection.prepareCall(
|
||||
"{call ADD_INVOICE(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
return ctrlResultSet;
|
||||
verify(callableStatement).close();
|
||||
}
|
||||
|
||||
private void initializeAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
|
||||
ResultSet proceduresResultSet = mock(ResultSet.class);
|
||||
ResultSet procedureColumnsResultSet = mock(ResultSet.class);
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("Oracle");
|
||||
given(databaseMetaData.getUserName()).willReturn("ME");
|
||||
given(databaseMetaData.storesUpperCaseIdentifiers()).willReturn(true);
|
||||
given(databaseMetaData.getProcedures("", "ME", "ADD_INVOICE")).willReturn(proceduresResultSet);
|
||||
given(databaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null)).willReturn(procedureColumnsResultSet);
|
||||
|
||||
given(proceduresResultSet.next()).willReturn(true, false);
|
||||
given(proceduresResultSet.getString("PROCEDURE_NAME")).willReturn("add_invoice");
|
||||
|
||||
given(procedureColumnsResultSet.next()).willReturn(true, true, true, false);
|
||||
given(procedureColumnsResultSet.getInt("DATA_TYPE")).willReturn(4);
|
||||
if (isFunction) {
|
||||
given(procedureColumnsResultSet.getString("COLUMN_NAME")).willReturn(null,"amount", "custid");
|
||||
given(procedureColumnsResultSet.getInt("COLUMN_TYPE")).willReturn(5, 1, 1);
|
||||
given(connection.prepareCall("{? = call ADD_INVOICE(?, ?)}")).willReturn(callableStatement);
|
||||
given(callableStatement.getObject(1)).willReturn(4L);
|
||||
}
|
||||
else {
|
||||
given(procedureColumnsResultSet.getString("COLUMN_NAME")).willReturn("amount", "custid", "newid");
|
||||
given(procedureColumnsResultSet.getInt("COLUMN_TYPE")).willReturn(1, 1, 4);
|
||||
given(connection.prepareCall("{call ADD_INVOICE(?, ?, ?)}")).willReturn(callableStatement);
|
||||
given(callableStatement.getObject(3)).willReturn(4L);
|
||||
}
|
||||
given(callableStatement.getUpdateCount()).willReturn(-1);
|
||||
}
|
||||
|
||||
private void verifyAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
|
||||
ResultSet proceduresResultSet = databaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
|
||||
ResultSet procedureColumnsResultSet = databaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
|
||||
if (isFunction) {
|
||||
verify(callableStatement).registerOutParameter(1, 4);
|
||||
verify(callableStatement).setObject(2, 1103, 4);
|
||||
verify(callableStatement).setObject(3, 3, 4);
|
||||
}
|
||||
else {
|
||||
verify(callableStatement).setObject(1, 1103, 4);
|
||||
verify(callableStatement).setObject(2, 3, 4);
|
||||
verify(callableStatement).registerOutParameter(3, 4);
|
||||
}
|
||||
verify(callableStatement).close();
|
||||
verify(proceduresResultSet).close();
|
||||
verify(procedureColumnsResultSet).close();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,105 +16,71 @@
|
||||
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
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.ResultSet;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
/**
|
||||
* Mock object based tests for SimpleJdbcInsert.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcInsertTests extends TestCase {
|
||||
public class SimpleJdbcInsertTests {
|
||||
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@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();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
private Connection connection;
|
||||
private DatabaseMetaData databaseMetaData;
|
||||
private DataSource dataSource;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = mock(Connection.class);
|
||||
databaseMetaData = mock(DatabaseMetaData.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
@After
|
||||
public void verifyClosed() throws Exception {
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoSuchTable() throws Exception {
|
||||
final String NO_SUCH_TABLE = "x";
|
||||
final String USER = "me";
|
||||
ResultSet resultSet = mock(ResultSet.class);
|
||||
given(resultSet.next()).willReturn(false);
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getDatabaseProductVersion()).willReturn("1.0");
|
||||
given(databaseMetaData.getUserName()).willReturn("me");
|
||||
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
|
||||
given(databaseMetaData.getTables(null, null, "x", null)).willReturn(resultSet);
|
||||
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, NO_SUCH_TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcInsert insert = new SimpleJdbcInsert(mockDataSource).withTableName(NO_SUCH_TABLE);
|
||||
SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource).withTableName("x");
|
||||
// Shouldn't succeed in inserting into table which doesn't exist
|
||||
thrown.expect(InvalidDataAccessApiUsageException.class);
|
||||
try {
|
||||
insert.execute(new HashMap());
|
||||
fail("Shouldn't succeed in inserting into table which doesn't exist");
|
||||
} catch (InvalidDataAccessApiUsageException ex) {
|
||||
// OK
|
||||
insert.execute(new HashMap<String, Object>());
|
||||
}
|
||||
finally {
|
||||
verify(resultSet).close();
|
||||
}
|
||||
}
|
||||
|
||||
public void testInsert() throws Exception {
|
||||
replay();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,27 +16,32 @@
|
||||
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.easymock.MockControl;
|
||||
import org.easymock.internal.ArrayMatcher;
|
||||
|
||||
import org.springframework.jdbc.core.BatchUpdateTestHelper;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
@@ -49,567 +54,321 @@ import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
* @author Juergen Hoeller
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcTemplateTests extends TestCase {
|
||||
public class SimpleJdbcTemplateTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
private static final String SQL = "sql";
|
||||
|
||||
private static final Object[] ARGS_ARRAY = { 24.7, "foo", new Object() };
|
||||
private static final Map<String, Object> ARGS_MAP;
|
||||
private static final MapSqlParameterSource ARGS_SOURCE;
|
||||
|
||||
static {
|
||||
ARGS_MAP = new HashMap<String, Object>(3);
|
||||
ARGS_SOURCE = new MapSqlParameterSource();
|
||||
for (int i = 0; i < ARGS_ARRAY.length; i++) {
|
||||
ARGS_MAP.put(String.valueOf(i), ARGS_ARRAY[i]);
|
||||
ARGS_SOURCE.addValue(String.valueOf(i), ARGS_ARRAY[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private JdbcOperations operations;
|
||||
private NamedParameterJdbcOperations namedParameterOperations;
|
||||
private SimpleJdbcTemplate template;
|
||||
private SimpleJdbcTemplate namedParameterTemplate;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.operations = mock(JdbcOperations.class);
|
||||
this.namedParameterOperations = mock(NamedParameterJdbcOperations.class);
|
||||
this.template = new SimpleJdbcTemplate(operations);
|
||||
this.namedParameterTemplate = new SimpleJdbcTemplate(namedParameterOperations);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForIntWithoutArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR";
|
||||
int expectedResult = 666;
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForInt(sql);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
|
||||
assertSame(jo, jth.getJdbcOperations());
|
||||
|
||||
int result = jth.queryForInt(sql);
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
given(operations.queryForInt(SQL)).willReturn(666);
|
||||
int result = template.queryForInt(SQL);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForIntWithArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForInt(sql, new Object[]{arg1, arg2});
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
int result = jth.queryForInt(sql, arg1, arg2);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForInt(SQL, new Object[] { 24, "foo" })).willReturn(666);
|
||||
int result = template.queryForInt(SQL, 24, "foo");
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForIntWithMap() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
Map<String, Object> args = new HashMap<String, Object>(2);
|
||||
args.put("id", arg1);
|
||||
args.put("xy", arg2);
|
||||
npjo.queryForInt(sql, args);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
|
||||
int result = jth.queryForInt(sql, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
args.put("id", 24);
|
||||
args.put("xy", "foo");
|
||||
given(namedParameterOperations.queryForInt(SQL, args)).willReturn(666);
|
||||
int result = namedParameterTemplate.queryForInt(SQL, args);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForIntWitSqlParameterSource() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
SqlParameterSource args = new MapSqlParameterSource().addValue("id", arg1).addValue("xy", arg2);
|
||||
npjo.queryForInt(sql, args);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
|
||||
int result = jth.queryForInt(sql, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
SqlParameterSource args = new MapSqlParameterSource().addValue("id", 24).addValue("xy", "foo");
|
||||
given(namedParameterOperations.queryForInt(SQL, args)).willReturn(666);
|
||||
int result = namedParameterTemplate.queryForInt(SQL, args);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForLongWithoutArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR";
|
||||
long expectedResult = 666;
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForLong(sql);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
long result = jth.queryForLong(sql);
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
given(operations.queryForLong(SQL)).willReturn((long) 666);
|
||||
long result = template.queryForLong(SQL);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForLongWithArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
|
||||
long expectedResult = 666;
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForLong(sql, new Object[]{arg1, arg2, arg3});
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
long result = jth.queryForLong(sql, arg1, arg2, arg3);
|
||||
given(operations.queryForLong(SQL, ARGS_ARRAY)).willReturn(expectedResult);
|
||||
long result = template.queryForLong(SQL, ARGS_ARRAY);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithoutArgs() throws Exception {
|
||||
String sql = "SELECT SYSDATE FROM DUAL";
|
||||
Date expectedResult = new Date();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, Date.class);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, Date.class)).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, Date.class);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithArgs() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
|
||||
).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, Date.class,ARGS_ARRAY);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithArgArray() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Object args = new Object[] {arg1, arg2, arg3};
|
||||
Date result = jth.queryForObject(sql, Date.class, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
|
||||
).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, Date.class, ARGS_ARRAY);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithMap() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, ARGS_ARRAY, Date.class)
|
||||
).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, Date.class, ARGS_ARRAY);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithRowMapperAndWithoutArgs() throws Exception {
|
||||
String sql = "SELECT SYSDATE FROM DUAL";
|
||||
Date expectedResult = new Date();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
@Override
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, rm);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, rm)).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, rm);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithRowMapperAndArgs() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
@Override
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(SQL, ARGS_ARRAY, rm)
|
||||
).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(SQL, rm, ARGS_ARRAY);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForObjectWithRowMapperAndMap() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
@Override
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
given(operations.queryForObject(sql, ARGS_ARRAY, rm)
|
||||
).willReturn(expectedResult);
|
||||
Date result = template.queryForObject(sql, rm, ARGS_ARRAY);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithoutArgs() throws Exception {
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{}, Collections.singletonList(new Object()));
|
||||
List<Map<String, Object>> expectedResult = mockListMapResult();
|
||||
given(operations.queryForList(SQL)).willReturn(expectedResult);
|
||||
List<Map<String, Object>> result = template.queryForList(SQL);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithArgs() throws Exception {
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{1, 2, 3}, new LinkedList());
|
||||
List<Map<String, Object>> expectedResult = mockListMapResult();
|
||||
given(operations.queryForList(SQL, 1, 2, 3)).willReturn(expectedResult);
|
||||
List<Map<String, Object>> result = template.queryForList(SQL, 1,2,3);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
|
||||
List<Map<String, Object>> expectedResult = mockListMapResult();
|
||||
given(namedParameterOperations.queryForList(SQL, ARGS_MAP)).willReturn(expectedResult);
|
||||
List<Map<String, Object>> result = namedParameterTemplate.queryForList(SQL, ARGS_MAP);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForListWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
|
||||
List<Map<String, Object>> expectedResult = mockListMapResult();
|
||||
given(namedParameterOperations.queryForList(SQL, ARGS_SOURCE)).willReturn(expectedResult);
|
||||
List<Map<String, Object>> result = namedParameterTemplate.queryForList(SQL, ARGS_SOURCE);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForMapWithoutArgs() throws Exception {
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{}, new HashMap());
|
||||
Map<String, Object> expectedResult = new HashMap<String, Object>();
|
||||
given(operations.queryForMap(SQL)).willReturn(expectedResult);
|
||||
Map<String, Object> result = template.queryForMap(SQL);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForMapWithArgs() throws Exception {
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{1, 2, 3}, new HashMap());
|
||||
// TODO test generic type
|
||||
Map<String, Object> expectedResult = new HashMap<String, Object>();
|
||||
given(operations.queryForMap(SQL, 1, 2, 3)).willReturn(expectedResult);
|
||||
Map<String, Object> result = template.queryForMap(SQL, 1,2,3);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForMapWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
|
||||
Map<String, Object> expectedResult = new HashMap<String, Object>();
|
||||
given(namedParameterOperations.queryForMap(SQL, ARGS_MAP)).willReturn(expectedResult);
|
||||
Map<String, Object> result = namedParameterTemplate.queryForMap(SQL, ARGS_MAP);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryForMapWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
|
||||
Map<String, Object> expectedResult = new HashMap<String, Object>();
|
||||
given(namedParameterOperations.queryForMap(SQL, ARGS_SOURCE)).willReturn(expectedResult);
|
||||
Map<String, Object> result = namedParameterTemplate.queryForMap(SQL, ARGS_SOURCE);
|
||||
assertSame(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateWithoutArgs() throws Exception {
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{}, 666);
|
||||
given(operations.update(SQL)).willReturn(666);
|
||||
int result = template.update(SQL);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateWithArgs() throws Exception {
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{1, 2, 3}, 666);
|
||||
given(operations.update(SQL, 1, 2, 3)).willReturn(666);
|
||||
int result = template.update(SQL, 1, 2, 3);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
|
||||
given(namedParameterOperations.update(SQL, ARGS_MAP)).willReturn(666);
|
||||
int result = namedParameterTemplate.update(SQL, ARGS_MAP);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
|
||||
}
|
||||
|
||||
private Object testDelegation(String methodName, Object[] typedArgs, Object[] varargs, Object expectedResult) throws Exception {
|
||||
Class[] unifiedTypes;
|
||||
Object[] unifiedArgs;
|
||||
Class[] unifiedTypes2;
|
||||
Object[] unifiedArgs2;
|
||||
boolean namedParameters = false;
|
||||
|
||||
if (varargs != null && varargs.length > 0) {
|
||||
// Allow for Map
|
||||
if (varargs[0].getClass().equals(HashMap.class)) {
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = Map.class;
|
||||
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
namedParameters = true;
|
||||
}
|
||||
else if (varargs[0].getClass().equals(MapSqlParameterSource.class)) {
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = SqlParameterSource.class;
|
||||
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
namedParameters = true;
|
||||
}
|
||||
else {
|
||||
// Allow for varargs.length
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < unifiedTypes.length - 1; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = Object[].class;
|
||||
unifiedArgs[unifiedTypes.length - 1] = varargs;
|
||||
}
|
||||
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
}
|
||||
else {
|
||||
unifiedTypes = new Class[typedArgs.length];
|
||||
unifiedTypes2 = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length];
|
||||
unifiedArgs2 = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = unifiedTypes2[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = unifiedArgs2[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes2[unifiedTypes2.length - 1] = Object[].class;
|
||||
unifiedArgs2[unifiedArgs2.length - 1] = new Object[]{};
|
||||
}
|
||||
|
||||
MockControl mc;
|
||||
JdbcOperations jo = null;
|
||||
NamedParameterJdbcOperations npjo = null;
|
||||
Method joMethod = null;
|
||||
SimpleJdbcTemplate jth = null;
|
||||
|
||||
if (namedParameters) {
|
||||
mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
joMethod = NamedParameterJdbcOperations.class.getMethod(methodName, unifiedTypes);
|
||||
joMethod.invoke(npjo, unifiedArgs);
|
||||
jth = new SimpleJdbcTemplate(npjo);
|
||||
}
|
||||
else {
|
||||
mc = MockControl.createControl(JdbcOperations.class);
|
||||
jo = (JdbcOperations) mc.getMock();
|
||||
joMethod = JdbcOperations.class.getMethod(methodName, unifiedTypes);
|
||||
joMethod.invoke(jo, unifiedArgs);
|
||||
jth = new SimpleJdbcTemplate(jo);
|
||||
}
|
||||
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
|
||||
if (joMethod.getReturnType().isPrimitive()) {
|
||||
// TODO bit of a hack with autoboxing passing up Integer when the return
|
||||
// type is an int
|
||||
mc.setReturnValue(((Integer) expectedResult).intValue());
|
||||
}
|
||||
else {
|
||||
mc.setReturnValue(expectedResult);
|
||||
}
|
||||
mc.replay();
|
||||
|
||||
Method jthMethod = SimpleJdbcTemplate.class.getMethod(methodName, unifiedTypes2);
|
||||
Object result = jthMethod.invoke(jth, unifiedArgs2);
|
||||
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
|
||||
return result;
|
||||
given(namedParameterOperations.update(SQL, ARGS_SOURCE)).willReturn(666);
|
||||
int result = namedParameterTemplate.update(SQL, ARGS_SOURCE);
|
||||
assertEquals(666, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithSqlParameterSource() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
PreparedStatement preparedStatement = setupBatchOperation();
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource("id", 100);
|
||||
ids[1] = new MapSqlParameterSource("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
int[] actualRowsAffected = template.batchUpdate("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
assertEquals(1, actualRowsAffected[0]);
|
||||
assertEquals(2, actualRowsAffected[1]);
|
||||
verify(preparedStatement).setObject(1, 100);
|
||||
verify(preparedStatement).setObject(1, 200);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithListOfObjectArrays() throws Exception {
|
||||
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] {100});
|
||||
ids.add(new Object[] {200});
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
PreparedStatement preparedStatement = setupBatchOperation();
|
||||
List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] { 100 });
|
||||
ids.add(new Object[] { 200 });
|
||||
int[] actualRowsAffected = template.batchUpdate(SQL, ids);
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
assertEquals(1, actualRowsAffected[0]);
|
||||
assertEquals(2, actualRowsAffected[1]);
|
||||
verify(preparedStatement).setObject(1, 100);
|
||||
verify(preparedStatement).setObject(1, 200);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception {
|
||||
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] {100});
|
||||
ids.add(new Object[] {200});
|
||||
final int[] sqlTypes = new int[] {Types.NUMERIC};
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids, sqlTypes);
|
||||
|
||||
int[] sqlTypes = new int[] { Types.NUMERIC };
|
||||
PreparedStatement preparedStatement = setupBatchOperation();
|
||||
List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] { 100 });
|
||||
ids.add(new Object[] { 200 });
|
||||
int[] actualRowsAffected = template.batchUpdate(SQL, ids, sqlTypes);
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
assertEquals(1, actualRowsAffected[0]);
|
||||
assertEquals(2, actualRowsAffected[1]);
|
||||
verify(preparedStatement).setObject(1, 100, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(1, 200, Types.NUMERIC);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
private PreparedStatement setupBatchOperation() throws SQLException {
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement preparedStatement = mock(PreparedStatement.class);
|
||||
DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(preparedStatement.getConnection()).willReturn(connection);
|
||||
given(preparedStatement.executeBatch()).willReturn(new int[] { 1, 2 });
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MySQL");
|
||||
given(databaseMetaData.supportsBatchUpdates()).willReturn(true);
|
||||
given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
template = new SimpleJdbcTemplate(new JdbcTemplate(dataSource, false));
|
||||
return preparedStatement;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> mockListMapResult() {
|
||||
return new LinkedList<Map<String, Object>>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,151 +1,81 @@
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.springframework.jdbc.core.metadata.TableMetaDataContext;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
import org.easymock.MockControl;
|
||||
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.verify;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.sql.Types;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
import org.springframework.jdbc.core.metadata.TableMetaDataContext;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
|
||||
/**
|
||||
* Mock object based tests for TableMetaDataContext.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class TableMetaDataContextTests extends TestCase {
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
public class TableMetaDataContextTests {
|
||||
|
||||
private Connection connection;
|
||||
private DataSource dataSource;
|
||||
private DatabaseMetaData databaseMetaData;
|
||||
|
||||
private TableMetaDataContext context = new TableMetaDataContext();
|
||||
|
||||
@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();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
connection = mock(Connection.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
databaseMetaData = mock(DatabaseMetaData.class);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
public void verifyClosed() throws Exception {
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
|
||||
final String TABLE = "customers";
|
||||
final String USER = "me";
|
||||
|
||||
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(true);
|
||||
mockMetaDataResultSet.getString("TABLE_CAT");
|
||||
ctrlMetaDataResultSet.setReturnValue(null);
|
||||
mockMetaDataResultSet.getString("TABLE_SCHEM");
|
||||
ctrlMetaDataResultSet.setReturnValue(USER);
|
||||
mockMetaDataResultSet.getString("TABLE_NAME");
|
||||
ctrlMetaDataResultSet.setReturnValue(TABLE);
|
||||
mockMetaDataResultSet.getString("TABLE_TYPE");
|
||||
ctrlMetaDataResultSet.setReturnValue("TABLE");
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(false);
|
||||
mockMetaDataResultSet.close();
|
||||
ctrlMetaDataResultSet.setVoidCallable();
|
||||
ResultSet metaDataResultSet = mock(ResultSet.class);
|
||||
given(metaDataResultSet.next()).willReturn(true, false);
|
||||
given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
|
||||
given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
|
||||
given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");
|
||||
|
||||
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("id");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("name");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.VARCHAR);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("customersince");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.DATE);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("version");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.NUMERIC);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.close();
|
||||
ctrlColumnsResultSet.setVoidCallable();
|
||||
ResultSet columnsResultSet = mock(ResultSet.class);
|
||||
given(columnsResultSet.next()).willReturn(
|
||||
true, true, true, true, false);
|
||||
given(columnsResultSet.getString("COLUMN_NAME")).willReturn(
|
||||
"id", "name", "customersince", "version");
|
||||
given(columnsResultSet.getInt("DATA_TYPE")).willReturn(
|
||||
Types.INTEGER, Types.VARCHAR, Types.DATE, Types.NUMERIC);
|
||||
given(columnsResultSet.getBoolean("NULLABLE")).willReturn(
|
||||
false, true, true, false);
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
|
||||
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
|
||||
|
||||
ctrlMetaDataResultSet.replay();
|
||||
ctrlColumnsResultSet.replay();
|
||||
replay();
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
|
||||
given(databaseMetaData.getUserName()).willReturn(USER);
|
||||
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
|
||||
given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
|
||||
given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);
|
||||
|
||||
MapSqlParameterSource map = new MapSqlParameterSource();
|
||||
map.addValue("id", 1);
|
||||
@@ -156,88 +86,59 @@ public class TableMetaDataContextTests extends TestCase {
|
||||
map.registerSqlType("version", Types.NUMERIC);
|
||||
|
||||
context.setTableName(TABLE);
|
||||
context.processMetaData(mockDataSource, new ArrayList<String>(), new String[] {});
|
||||
context.processMetaData(dataSource, new ArrayList<String>(), new String[] {});
|
||||
|
||||
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
|
||||
|
||||
assertEquals("wrong number of parameters: ", 4, values.size());
|
||||
assertTrue("id not wrapped with type info", values.get(0) instanceof Number);
|
||||
assertTrue("name not wrapped with type info", values.get(1) instanceof String);
|
||||
assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue);
|
||||
assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue);
|
||||
assertTrue("date wrapped with type info",
|
||||
values.get(2) instanceof SqlParameterValue);
|
||||
assertTrue("version wrapped with type info",
|
||||
values.get(3) instanceof SqlParameterValue);
|
||||
verify(metaDataResultSet, atLeastOnce()).next();
|
||||
verify(columnsResultSet, atLeastOnce()).next();
|
||||
verify(metaDataResultSet).close();
|
||||
verify(columnsResultSet).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTableWithSingleColumnGeneratedKey() throws Exception {
|
||||
final String TABLE = "customers";
|
||||
final String USER = "me";
|
||||
|
||||
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(true);
|
||||
mockMetaDataResultSet.getString("TABLE_CAT");
|
||||
ctrlMetaDataResultSet.setReturnValue(null);
|
||||
mockMetaDataResultSet.getString("TABLE_SCHEM");
|
||||
ctrlMetaDataResultSet.setReturnValue(USER);
|
||||
mockMetaDataResultSet.getString("TABLE_NAME");
|
||||
ctrlMetaDataResultSet.setReturnValue(TABLE);
|
||||
mockMetaDataResultSet.getString("TABLE_TYPE");
|
||||
ctrlMetaDataResultSet.setReturnValue("TABLE");
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(false);
|
||||
mockMetaDataResultSet.close();
|
||||
ctrlMetaDataResultSet.setVoidCallable();
|
||||
ResultSet metaDataResultSet = mock(ResultSet.class);
|
||||
given(metaDataResultSet.next()).willReturn(true, false);
|
||||
given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
|
||||
given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
|
||||
given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");
|
||||
|
||||
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("id");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.close();
|
||||
ctrlColumnsResultSet.setVoidCallable();
|
||||
ResultSet columnsResultSet = mock(ResultSet.class);
|
||||
given(columnsResultSet.next()).willReturn(true, false);
|
||||
given(columnsResultSet.getString("COLUMN_NAME")).willReturn("id");
|
||||
given(columnsResultSet.getInt("DATA_TYPE")).willReturn(Types.INTEGER);
|
||||
given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false);
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
|
||||
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
|
||||
|
||||
ctrlMetaDataResultSet.replay();
|
||||
ctrlColumnsResultSet.replay();
|
||||
replay();
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
|
||||
given(databaseMetaData.getUserName()).willReturn(USER);
|
||||
given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
|
||||
given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
|
||||
given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);
|
||||
|
||||
MapSqlParameterSource map = new MapSqlParameterSource();
|
||||
|
||||
String[] keyCols = new String[] {"id"};
|
||||
|
||||
String[] keyCols = new String[] { "id" };
|
||||
context.setTableName(TABLE);
|
||||
context.processMetaData(mockDataSource, new ArrayList<String>(), keyCols);
|
||||
|
||||
context.processMetaData(dataSource, new ArrayList<String>(), keyCols);
|
||||
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
|
||||
|
||||
String insertString = context.createInsertString(keyCols);
|
||||
|
||||
assertEquals("wrong number of parameters: ", 0, values.size());
|
||||
assertEquals("empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString);
|
||||
verify(metaDataResultSet, atLeastOnce()).next();
|
||||
verify(columnsResultSet, atLeastOnce()).next();
|
||||
verify(metaDataResultSet).close();
|
||||
verify(columnsResultSet).close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,72 +16,53 @@
|
||||
|
||||
package org.springframework.jdbc.core.support;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class JdbcBeanDefinitionReaderTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
public class JdbcBeanDefinitionReaderTests {
|
||||
|
||||
@Test
|
||||
public void testValid() throws Exception {
|
||||
String sql = "SELECT NAME AS NAME, PROPERTY AS PROPERTY, VALUE AS VALUE FROM T";
|
||||
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.next(), true, 2);
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.next(), false);
|
||||
Connection connection = mock(Connection.class);
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
|
||||
// first row
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "(class)");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "org.springframework.beans.TestBean");
|
||||
ResultSet resultSet = mock(ResultSet.class);
|
||||
given(resultSet.next()).willReturn(true, true, false);
|
||||
given(resultSet.getString(1)).willReturn("one", "one");
|
||||
given(resultSet.getString(2)).willReturn("(class)", "age");
|
||||
given(resultSet.getString(3)).willReturn("org.springframework.beans.TestBean", "53");
|
||||
|
||||
// second row
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "age");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "53");
|
||||
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
MockControl ctrlStatement = MockControl.createControl(Statement.class);
|
||||
Statement mockStatement = (Statement) ctrlStatement.getMock();
|
||||
ctrlStatement.expectAndReturn(mockStatement.executeQuery(sql), mockResultSet);
|
||||
if (debugEnabled) {
|
||||
ctrlStatement.expectAndReturn(mockStatement.getWarnings(), null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
ctrlStatement.replay();
|
||||
replay();
|
||||
Statement statement = mock(Statement.class);
|
||||
given(statement.executeQuery(sql)).willReturn(resultSet);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
JdbcBeanDefinitionReader reader = new JdbcBeanDefinitionReader(bf);
|
||||
reader.setDataSource(mockDataSource);
|
||||
reader.setDataSource(dataSource);
|
||||
reader.loadBeanDefinitions(sql);
|
||||
assertEquals("Incorrect number of bean definitions", 1, bf.getBeanDefinitionCount());
|
||||
TestBean tb = (TestBean) bf.getBean("one");
|
||||
assertEquals("Age in TestBean was wrong.", 53, tb.getAge());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
ctrlStatement.verify();
|
||||
verify(resultSet).close();
|
||||
verify(statement).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -16,14 +16,20 @@
|
||||
|
||||
package org.springframework.jdbc.core.support;
|
||||
|
||||
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 java.io.IOException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.IncorrectResultSizeDataAccessException;
|
||||
import org.springframework.jdbc.LobRetrievalFailureException;
|
||||
@@ -33,32 +39,19 @@ import org.springframework.jdbc.support.lob.LobHandler;
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
*/
|
||||
public class LobSupportTests extends TestCase {
|
||||
public class LobSupportTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void testCreatingPreparedStatementCallback() throws SQLException {
|
||||
// - return value should match
|
||||
// - lob creator should be closed
|
||||
// - set return value should be called
|
||||
// - execute update should be called
|
||||
LobHandler handler = mock(LobHandler.class);
|
||||
LobCreator creator = mock(LobCreator.class);
|
||||
PreparedStatement ps = mock(PreparedStatement.class);
|
||||
|
||||
MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
LobHandler handler = (LobHandler)lobHandlerControl.getMock();
|
||||
|
||||
MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
LobCreator creator = (LobCreator)lobCreatorControl.getMock();
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement)psControl.getMock();
|
||||
|
||||
handler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(creator);
|
||||
ps.executeUpdate();
|
||||
psControl.setReturnValue(3);
|
||||
creator.close();
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
psControl.replay();
|
||||
given(handler.getLobCreator()).willReturn(creator);
|
||||
given(ps.executeUpdate()).willReturn(3);
|
||||
|
||||
class SetValuesCalled {
|
||||
boolean b = false;
|
||||
@@ -66,9 +59,8 @@ public class LobSupportTests extends TestCase {
|
||||
|
||||
final SetValuesCalled svc = new SetValuesCalled();
|
||||
|
||||
AbstractLobCreatingPreparedStatementCallback psc =
|
||||
new AbstractLobCreatingPreparedStatementCallback(handler) {
|
||||
|
||||
AbstractLobCreatingPreparedStatementCallback psc = new AbstractLobCreatingPreparedStatementCallback(
|
||||
handler) {
|
||||
@Override
|
||||
protected void setValues(PreparedStatement ps, LobCreator lobCreator)
|
||||
throws SQLException, DataAccessException {
|
||||
@@ -77,85 +69,62 @@ public class LobSupportTests extends TestCase {
|
||||
};
|
||||
|
||||
assertEquals(new Integer(3), psc.doInPreparedStatement(ps));
|
||||
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
psControl.verify();
|
||||
assertTrue(svc.b);
|
||||
verify(creator).close();
|
||||
verify(handler).getLobCreator();
|
||||
verify(ps).executeUpdate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(false);
|
||||
rsetControl.replay();
|
||||
|
||||
ResultSet rset = mock(ResultSet.class);
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
thrown.expect(IncorrectResultSizeDataAccessException.class);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("IncorrectResultSizeDataAccessException should have been thrown");
|
||||
} catch (IncorrectResultSizeDataAccessException e) {
|
||||
// expected
|
||||
}
|
||||
finally {
|
||||
verify(rset).next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
// see if it's called
|
||||
rset.clearWarnings();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(false);
|
||||
rsetControl.replay();
|
||||
|
||||
ResultSet rset = mock(ResultSet.class);
|
||||
given(rset.next()).willReturn(true, false);
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
lobRse.extractData(rset);
|
||||
rsetControl.verify();
|
||||
verify(rset).clearWarnings();
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorMultipleRows() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
// see if it's called
|
||||
rset.clearWarnings();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
rsetControl.replay();
|
||||
|
||||
@Test
|
||||
public void testAbstractLobStreamingResultSetExtractorMultipleRows()
|
||||
throws SQLException {
|
||||
ResultSet rset = mock(ResultSet.class);
|
||||
given(rset.next()).willReturn(true, true, false);
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
thrown.expect(IncorrectResultSizeDataAccessException.class);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("IncorrectResultSizeDataAccessException should have been thrown");
|
||||
} catch (IncorrectResultSizeDataAccessException e) {
|
||||
// expected
|
||||
}
|
||||
rsetControl.verify();
|
||||
finally {
|
||||
verify(rset).clearWarnings();
|
||||
}
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorCorrectException() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
rsetControl.replay();
|
||||
|
||||
@Test
|
||||
public void testAbstractLobStreamingResultSetExtractorCorrectException()
|
||||
throws SQLException {
|
||||
ResultSet rset = mock(ResultSet.class);
|
||||
given(rset.next()).willReturn(true);
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(true);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("LobRetrievalFailureException should have been thrown");
|
||||
} catch (LobRetrievalFailureException e) {
|
||||
// expected
|
||||
}
|
||||
rsetControl.verify();
|
||||
thrown.expect(LobRetrievalFailureException.class);
|
||||
lobRse.extractData(rset);
|
||||
}
|
||||
|
||||
private AbstractLobStreamingResultSetExtractor getResultSetExtractor(final boolean ex) {
|
||||
AbstractLobStreamingResultSetExtractor lobRse = new AbstractLobStreamingResultSetExtractor() {
|
||||
|
||||
@Override
|
||||
protected void streamData(ResultSet rs) throws SQLException, IOException {
|
||||
if (ex) {
|
||||
|
||||
@@ -15,18 +15,28 @@
|
||||
*/
|
||||
package org.springframework.jdbc.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.ArgumentsMatcher;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
|
||||
@@ -46,179 +56,96 @@ import org.springframework.jdbc.support.lob.LobHandler;
|
||||
*
|
||||
* @author Alef Arendsen
|
||||
*/
|
||||
public class SqlLobValueTests extends TestCase {
|
||||
public class SqlLobValueTests {
|
||||
|
||||
private MockControl psControl;
|
||||
private PreparedStatement ps;
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockControl lobHandlerControl;
|
||||
private PreparedStatement preparedStatement;
|
||||
private LobHandler handler;
|
||||
|
||||
private MockControl lobCreatorControl;
|
||||
private LobCreator creator;
|
||||
|
||||
@Override
|
||||
@Captor
|
||||
private ArgumentCaptor<InputStream> inputStreamCaptor;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
// create preparedstatement
|
||||
psControl = MockControl.createControl(PreparedStatement.class);
|
||||
ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
// create handler controler
|
||||
lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
handler = (LobHandler) lobHandlerControl.getMock();
|
||||
|
||||
// create creator control
|
||||
lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
creator = (LobCreator) lobCreatorControl.getMock();
|
||||
|
||||
// set initial state
|
||||
handler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(creator);
|
||||
}
|
||||
|
||||
private void replay() {
|
||||
psControl.replay();
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
MockitoAnnotations.initMocks(this);
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
handler = mock(LobHandler.class);
|
||||
creator = mock(LobCreator.class);
|
||||
given(handler.getLobCreator()).willReturn(creator);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test1() throws SQLException {
|
||||
byte[] testBytes = "Bla".getBytes();
|
||||
creator.setBlobAsBytes(ps, 1, testBytes);
|
||||
replay();
|
||||
SqlLobValue lob = new SqlLobValue(testBytes, handler);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
verify(creator).setBlobAsBytes(preparedStatement, 1, testBytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test2() throws SQLException {
|
||||
String testString = "Bla";
|
||||
|
||||
creator.setBlobAsBytes(ps, 1, testString.getBytes());
|
||||
// set a matcher to match the byte array!
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
@Override
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
byte[] one = (byte[]) arg0[2];
|
||||
byte[] two = (byte[]) arg1[2];
|
||||
return Arrays.equals(one, two);
|
||||
}
|
||||
@Override
|
||||
public String toString(Object[] arg0) {
|
||||
return "bla";
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(testString, handler);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
verify(creator).setBlobAsBytes(preparedStatement, 1, testString.getBytes());
|
||||
}
|
||||
|
||||
public void test3()
|
||||
throws SQLException {
|
||||
|
||||
Date testContent = new Date();
|
||||
|
||||
SqlLobValue lob =
|
||||
new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
@Test
|
||||
public void test3() throws SQLException {
|
||||
SqlLobValue lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test4() throws SQLException {
|
||||
String testContent = "Bla";
|
||||
creator.setClobAsString(ps, 1, testContent);
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(testContent, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
verify(creator).setClobAsString(preparedStatement, 1, testContent);
|
||||
}
|
||||
|
||||
public void test5() throws SQLException {
|
||||
@Test
|
||||
public void test5() throws Exception {
|
||||
byte[] testContent = "Bla".getBytes();
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
|
||||
creator.setClobAsAsciiStream(ps, 1, bais, 3);
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
@Override
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
// for now, match always
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public String toString(Object[] arg0) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(new ByteArrayInputStream(testContent), 3, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
verify(creator).setClobAsAsciiStream(eq(preparedStatement), eq(1), inputStreamCaptor.capture(), eq(3));
|
||||
byte[] bytes = new byte[3];
|
||||
inputStreamCaptor.getValue().read(bytes );
|
||||
assertThat(bytes, equalTo(testContent));
|
||||
}
|
||||
|
||||
public void test6()throws SQLException {
|
||||
@Test
|
||||
public void test6() throws SQLException {
|
||||
byte[] testContent = "Bla".getBytes();
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
|
||||
InputStreamReader reader = new InputStreamReader(bais);
|
||||
creator.setClobAsCharacterStream(ps, 1, reader, 3);
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
@Override
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
// for now, match always
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public String toString(Object[] arg0) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(reader, 3, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
verify(creator).setClobAsCharacterStream(eq(preparedStatement), eq(1), eq(reader), eq(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test7() throws SQLException {
|
||||
Date testContent = new Date();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue("bla".getBytes());
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOtherConstructors() throws SQLException {
|
||||
// a bit BS, but we need to test them, as long as they don't throw exceptions
|
||||
|
||||
SqlLobValue lob = new SqlLobValue("bla");
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
|
||||
try {
|
||||
lob = new SqlLobValue("bla".getBytes());
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
@@ -226,27 +153,27 @@ public class SqlLobValueTests extends TestCase {
|
||||
}
|
||||
|
||||
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new InputStreamReader(
|
||||
new ByteArrayInputStream("bla".getBytes())), 3);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream(
|
||||
"bla".getBytes())), 3);
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
|
||||
// same for BLOB
|
||||
lob = new SqlLobValue("bla");
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue("bla".getBytes());
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new InputStreamReader(
|
||||
new ByteArrayInputStream("bla".getBytes())), 3);
|
||||
lob = new SqlLobValue(new InputStreamReader(new ByteArrayInputStream(
|
||||
"bla".getBytes())), 3);
|
||||
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.BLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
@@ -254,28 +181,20 @@ public class SqlLobValueTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
public void testCorrectCleanup() throws SQLException {
|
||||
creator.setClobAsString(ps, 1, "Bla");
|
||||
creator.close();
|
||||
|
||||
replay();
|
||||
@Test
|
||||
public void testCorrectCleanup() throws SQLException {
|
||||
SqlLobValue lob = new SqlLobValue("Bla", handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
|
||||
lob.cleanup();
|
||||
|
||||
lobCreatorControl.verify();
|
||||
verify(creator).setClobAsString(preparedStatement, 1, "Bla");
|
||||
verify(creator).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOtherSqlType() throws SQLException {
|
||||
replay();
|
||||
SqlLobValue lob = new SqlLobValue("Bla", handler);
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.SMALLINT, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
lob.setTypeValue(preparedStatement, 1, Types.SMALLINT, "test");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,6 +16,19 @@
|
||||
|
||||
package org.springframework.jdbc.datasource;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
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.BDDMockito.willThrow;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
@@ -23,15 +36,16 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import javax.transaction.RollbackException;
|
||||
import javax.transaction.Status;
|
||||
import javax.transaction.SystemException;
|
||||
import javax.transaction.Transaction;
|
||||
import javax.transaction.TransactionManager;
|
||||
import javax.transaction.UserTransaction;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.support.StaticListableBeanFactory;
|
||||
import org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookup;
|
||||
import org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter;
|
||||
@@ -49,66 +63,73 @@ import org.springframework.transaction.support.TransactionTemplate;
|
||||
* @author Juergen Hoeller
|
||||
* @since 17.10.2005
|
||||
*/
|
||||
public class DataSourceJtaTransactionTests extends TestCase {
|
||||
public class DataSourceJtaTransactionTests {
|
||||
|
||||
private Connection connection;
|
||||
private DataSource dataSource;
|
||||
private UserTransaction userTransaction;
|
||||
private TransactionManager transactionManager;
|
||||
private Transaction transaction;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
connection =mock(Connection.class);
|
||||
dataSource = mock(DataSource.class);
|
||||
userTransaction = mock(UserTransaction.class);
|
||||
transactionManager = mock(TransactionManager.class);
|
||||
transaction = mock(Transaction.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
}
|
||||
|
||||
@After
|
||||
public void verifyTransactionSynchronizationManagerState() {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommit() throws Exception {
|
||||
doTestJtaTransaction(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollback() throws Exception {
|
||||
doTestJtaTransaction(true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransaction(final boolean rollback) throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
if (rollback) {
|
||||
ut.rollback();
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_NO_TRANSACTION,Status.STATUS_ACTIVE);
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.commit();
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
|
||||
}
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
@Override
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
Connection c = DataSourceUtils.getConnection(dataSource);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
|
||||
DataSourceUtils.releaseConnection(c, dataSource);
|
||||
|
||||
c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
c = DataSourceUtils.getConnection(dataSource);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
|
||||
DataSourceUtils.releaseConnection(c, dataSource);
|
||||
|
||||
if (rollback) {
|
||||
status.setRollbackOnly();
|
||||
@@ -116,49 +137,61 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
verify(userTransaction).begin();
|
||||
if (rollback) {
|
||||
verify(userTransaction).rollback();
|
||||
}
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true);
|
||||
}
|
||||
@@ -167,57 +200,22 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
final boolean rollback, final boolean openOuterConnection, final boolean accessAfterResume,
|
||||
final boolean useTransactionAwareDataSource) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 16);
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 5);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(5);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(5);
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(5);
|
||||
given(transactionManager.suspend()).willReturn(transaction);
|
||||
if (rollback) {
|
||||
ut.rollback();
|
||||
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE);
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.commit();
|
||||
given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
|
||||
}
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl conControl = MockControl.createControl(Connection.class);
|
||||
final Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
if (!openOuterConnection) {
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
}
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
given(connection.isReadOnly()).willReturn(true);
|
||||
|
||||
final DataSource dsToUse = useTransactionAwareDataSource ?
|
||||
new TransactionAwareDataSourceProxy(ds) : ds;
|
||||
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
|
||||
final TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
@@ -255,19 +253,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
try {
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
c.isReadOnly();
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
@@ -290,21 +275,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
|
||||
if (accessAfterResume) {
|
||||
try {
|
||||
if (!openOuterConnection) {
|
||||
dsControl.verify();
|
||||
dsControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
dsControl.replay();
|
||||
}
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
|
||||
if (!openOuterConnection) {
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
}
|
||||
@@ -322,15 +292,6 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
|
||||
else {
|
||||
if (openOuterConnection) {
|
||||
try {
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
}
|
||||
@@ -339,24 +300,38 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
verify(userTransaction, times(6)).begin();
|
||||
verify(transactionManager, times(5)).resume(transaction);
|
||||
if(rollback) {
|
||||
verify(userTransaction, times(5)).commit();
|
||||
verify(userTransaction).rollback();
|
||||
} else {
|
||||
verify(userTransaction, times(6)).commit();
|
||||
}
|
||||
if(accessAfterResume && !openOuterConnection) {
|
||||
verify(connection, times(7)).close();
|
||||
}
|
||||
else {
|
||||
verify(connection, times(6)).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true);
|
||||
}
|
||||
@@ -364,57 +339,28 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(
|
||||
final boolean requiresNew, boolean notSupported) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
if (notSupported) {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 1);
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_ACTIVE);
|
||||
given(transactionManager.suspend()).willReturn(transaction);
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_ACTIVE);
|
||||
}
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
if (notSupported) {
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(1);
|
||||
}
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
txControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
final MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
final Connection con2 = (Connection) con2Control.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con1, 1);
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con2, 1);
|
||||
con2.close();
|
||||
con2Control.setVoidCallable(1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
con1Control.replay();
|
||||
con2Control.replay();
|
||||
final DataSource dataSource = mock(DataSource.class);
|
||||
final Connection connection1 = mock(Connection.class);
|
||||
final Connection connection2 = mock(Connection.class);
|
||||
given(dataSource.getConnection()).willReturn(connection1, connection2);
|
||||
|
||||
final JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(notSupported ?
|
||||
TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS);
|
||||
@@ -426,8 +372,8 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
|
||||
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
|
||||
|
||||
TransactionTemplate tt2 = new TransactionTemplate(ptm);
|
||||
tt2.setPropagationBehavior(requiresNew ?
|
||||
@@ -438,55 +384,63 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con2, DataSourceUtils.getConnection(ds));
|
||||
assertSame(con2, DataSourceUtils.getConnection(ds));
|
||||
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
|
||||
assertSame(connection2, DataSourceUtils.getConnection(dataSource));
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
assertSame(connection1, DataSourceUtils.getConnection(dataSource));
|
||||
}
|
||||
});
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
txControl.verify();
|
||||
dsControl.verify();
|
||||
con1Control.verify();
|
||||
con2Control.verify();
|
||||
verify(userTransaction).begin();
|
||||
verify(userTransaction).commit();
|
||||
if (notSupported) {
|
||||
verify(transactionManager).resume(transaction);
|
||||
}
|
||||
verify(connection2).close();
|
||||
verify(connection1).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true);
|
||||
}
|
||||
@@ -494,57 +448,27 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
|
||||
final boolean openOuterConnection, final boolean useTransactionAwareDataSource) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_ACTIVE);
|
||||
if (suspendException) {
|
||||
tm.suspend();
|
||||
tmControl.setThrowable(new SystemException(), 1);
|
||||
given(transactionManager.suspend()).willThrow(new SystemException());
|
||||
}
|
||||
else {
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 1);
|
||||
ut.begin();
|
||||
utControl.setThrowable(new SystemException(), 1);
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(1);
|
||||
given(transactionManager.suspend()).willReturn(transaction);
|
||||
willThrow(new SystemException()).given(userTransaction).begin();
|
||||
}
|
||||
ut.rollback();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl conControl = MockControl.createControl(Connection.class);
|
||||
final Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
if (!openOuterConnection || useTransactionAwareDataSource) {
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
}
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
given(connection.isReadOnly()).willReturn(true);
|
||||
|
||||
final DataSource dsToUse = useTransactionAwareDataSource ?
|
||||
new TransactionAwareDataSourceProxy(ds) : ds;
|
||||
new TransactionAwareDataSourceProxy(dataSource) : dataSource;
|
||||
if (dsToUse instanceof TransactionAwareDataSourceProxy) {
|
||||
((TransactionAwareDataSourceProxy) dsToUse).setReobtainTransactionalConnections(true);
|
||||
}
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
|
||||
final TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
@@ -581,50 +505,19 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
try {
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
}
|
||||
finally {
|
||||
if (openOuterConnection) {
|
||||
try {
|
||||
dsControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
|
||||
if (useTransactionAwareDataSource) {
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
}
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
c.isReadOnly();
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
@@ -643,26 +536,30 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
|
||||
verify(userTransaction).begin();
|
||||
if(suspendException) {
|
||||
verify(userTransaction).rollback();
|
||||
}
|
||||
|
||||
if (suspendException) {
|
||||
verify(connection, atLeastOnce()).close();
|
||||
}
|
||||
else {
|
||||
verify(connection, never()).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut) {
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {
|
||||
|
||||
@Override
|
||||
protected void doRegisterAfterCompletionWithJtaTransaction(
|
||||
JtaTransactionObject txObject, final List synchronizations) {
|
||||
JtaTransactionObject txObject,
|
||||
final List<TransactionSynchronization> synchronizations)
|
||||
throws RollbackException, SystemException {
|
||||
Thread async = new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -679,24 +576,11 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
}
|
||||
};
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
utControl.reset();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
utControl.replay();
|
||||
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
final boolean releaseCon = (i != 1);
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
@@ -705,76 +589,44 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is existing transaction", !status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
Connection c = DataSourceUtils.getConnection(dataSource);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
|
||||
DataSourceUtils.releaseConnection(c, dataSource);
|
||||
|
||||
c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
c = DataSourceUtils.getConnection(dataSource);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource));
|
||||
if (releaseCon) {
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
DataSourceUtils.releaseConnection(c, dataSource);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!releaseCon) {
|
||||
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(dataSource));
|
||||
}
|
||||
else {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource));
|
||||
}
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
conControl.verify();
|
||||
dsControl.verify();
|
||||
utControl.verify();
|
||||
}
|
||||
verify(connection, times(3)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
|
||||
MockControl ds1Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds1 = (DataSource) ds1Control.getMock();
|
||||
MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.setReadOnly(true);
|
||||
con1Control.setVoidCallable(1);
|
||||
con1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
con1Control.setVoidCallable(1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
con1Control.replay();
|
||||
ds1Control.replay();
|
||||
given(userTransaction.getStatus()).willReturn(
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_NO_TRANSACTION,
|
||||
Status.STATUS_ACTIVE,
|
||||
Status.STATUS_ACTIVE);
|
||||
|
||||
final IsolationLevelDataSourceAdapter dsToUse = new IsolationLevelDataSourceAdapter();
|
||||
dsToUse.setTargetDataSource(ds1);
|
||||
dsToUse.setTargetDataSource(dataSource);
|
||||
dsToUse.afterPropertiesSet();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
|
||||
ptm.setAllowCustomIsolationLevels(true);
|
||||
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
@@ -783,7 +635,7 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
assertSame(connection, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
@@ -795,84 +647,57 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
assertSame(connection, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
ds1Control.verify();
|
||||
con1Control.verify();
|
||||
utControl.verify();
|
||||
verify(userTransaction, times(2)).begin();
|
||||
verify(userTransaction, times(2)).commit();
|
||||
verify(connection).setReadOnly(true);
|
||||
verify(connection).setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
verify(connection, times(2)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception {
|
||||
doTestJtaTransactionWithIsolationLevelDataSourceRouter(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception {
|
||||
doTestJtaTransactionWithIsolationLevelDataSourceRouter(true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransactionWithIsolationLevelDataSourceRouter(boolean dataSourceLookup) throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
given( userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
|
||||
|
||||
MockControl ds1Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds1 = (DataSource) ds1Control.getMock();
|
||||
MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
con1Control.replay();
|
||||
ds1Control.replay();
|
||||
final DataSource dataSource1 = mock(DataSource.class);
|
||||
final Connection connection1 = mock(Connection.class);
|
||||
given(dataSource1.getConnection()).willReturn(connection1);
|
||||
|
||||
MockControl ds2Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds2 = (DataSource) ds2Control.getMock();
|
||||
MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
final Connection con2 = (Connection) con2Control.getMock();
|
||||
ds2.getConnection();
|
||||
ds2Control.setReturnValue(con2, 1);
|
||||
con2.close();
|
||||
con2Control.setVoidCallable(1);
|
||||
con2Control.replay();
|
||||
ds2Control.replay();
|
||||
final DataSource dataSource2 = mock(DataSource.class);
|
||||
final Connection connection2 = mock(Connection.class);
|
||||
given(dataSource2.getConnection()).willReturn(connection2);
|
||||
|
||||
final IsolationLevelDataSourceRouter dsToUse = new IsolationLevelDataSourceRouter();
|
||||
Map targetDataSources = new HashMap();
|
||||
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
|
||||
if (dataSourceLookup) {
|
||||
targetDataSources.put("ISOLATION_REPEATABLE_READ", "ds2");
|
||||
dsToUse.setDefaultTargetDataSource("ds1");
|
||||
StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
|
||||
beanFactory.addBean("ds1", ds1);
|
||||
beanFactory.addBean("ds2", ds2);
|
||||
beanFactory.addBean("ds1", dataSource1);
|
||||
beanFactory.addBean("ds2", dataSource2);
|
||||
dsToUse.setDataSourceLookup(new BeanFactoryDataSourceLookup(beanFactory));
|
||||
}
|
||||
else {
|
||||
targetDataSources.put("ISOLATION_REPEATABLE_READ", ds2);
|
||||
dsToUse.setDefaultTargetDataSource(ds1);
|
||||
targetDataSources.put("ISOLATION_REPEATABLE_READ", dataSource2);
|
||||
dsToUse.setDefaultTargetDataSource(dataSource1);
|
||||
}
|
||||
dsToUse.setTargetDataSources(targetDataSources);
|
||||
dsToUse.afterPropertiesSet();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
|
||||
ptm.setAllowCustomIsolationLevels(true);
|
||||
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
@@ -881,7 +706,7 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
assertSame(connection1, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
@@ -892,26 +717,14 @@ public class DataSourceJtaTransactionTests extends TestCase {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con2, c);
|
||||
assertSame(connection2, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
ds1Control.verify();
|
||||
con1Control.verify();
|
||||
ds2Control.verify();
|
||||
con2Control.verify();
|
||||
utControl.verify();
|
||||
verify(userTransaction, times(2)).begin();
|
||||
verify(userTransaction, times(2)).commit();
|
||||
verify(connection1).close();
|
||||
verify(connection2).close();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,9 @@ package org.springframework.jdbc.datasource;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintWriter;
|
||||
@@ -25,7 +28,6 @@ import java.sql.Connection;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -42,100 +44,78 @@ public class DelegatingDataSourceTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.delegate = EasyMock.createMock(DataSource.class);
|
||||
this.delegate = mock(DataSource.class);
|
||||
this.dataSource = new DelegatingDataSource(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateGetConnection() throws Exception {
|
||||
Connection connection = EasyMock.createMock(Connection.class);
|
||||
EasyMock.expect(delegate.getConnection()).andReturn(connection);
|
||||
EasyMock.replay(delegate);
|
||||
Connection connection = mock(Connection.class);
|
||||
given(delegate.getConnection()).willReturn(connection);
|
||||
assertThat(dataSource.getConnection(), is(connection));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateGetConnectionWithUsernameAndPassword() throws Exception {
|
||||
Connection connection = EasyMock.createMock(Connection.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
String username = "username";
|
||||
String password = "password";
|
||||
EasyMock.expect(delegate.getConnection(username, password)).andReturn(connection);
|
||||
EasyMock.replay(delegate);
|
||||
given(delegate.getConnection(username, password)).willReturn(connection);
|
||||
assertThat(dataSource.getConnection(username, password), is(connection));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateGetLogWriter() throws Exception {
|
||||
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
|
||||
EasyMock.expect(delegate.getLogWriter()).andReturn(writer);
|
||||
EasyMock.replay(delegate);
|
||||
given(delegate.getLogWriter()).willReturn(writer);
|
||||
assertThat(dataSource.getLogWriter(), is(writer));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateSetLogWriter() throws Exception {
|
||||
PrintWriter writer = new PrintWriter(new ByteArrayOutputStream());
|
||||
delegate.setLogWriter(writer);
|
||||
EasyMock.expectLastCall();
|
||||
EasyMock.replay(delegate);
|
||||
dataSource.setLogWriter(writer);
|
||||
EasyMock.verify(delegate);
|
||||
verify(delegate).setLogWriter(writer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateGetLoginTimeout() throws Exception {
|
||||
int timeout = 123;
|
||||
EasyMock.expect(delegate.getLoginTimeout()).andReturn(timeout);
|
||||
EasyMock.replay(delegate);
|
||||
given(delegate.getLoginTimeout()).willReturn(timeout);
|
||||
assertThat(dataSource.getLoginTimeout(), is(timeout));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateSetLoginTimeoutWithSeconds() throws Exception {
|
||||
int timeout = 123;
|
||||
delegate.setLoginTimeout(timeout);
|
||||
EasyMock.expectLastCall();
|
||||
EasyMock.replay(delegate);
|
||||
dataSource.setLoginTimeout(timeout);
|
||||
EasyMock.verify(delegate);
|
||||
verify(delegate).setLoginTimeout(timeout);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateUnwrapWithoutImplementing() throws Exception {
|
||||
ExampleWrapper wrapper = EasyMock.createMock(ExampleWrapper.class);
|
||||
EasyMock.expect(delegate.unwrap(ExampleWrapper.class)).andReturn(wrapper);
|
||||
EasyMock.replay(delegate);
|
||||
ExampleWrapper wrapper = mock(ExampleWrapper.class);
|
||||
given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper);
|
||||
assertThat(dataSource.unwrap(ExampleWrapper.class), is(wrapper));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateUnwrapImplementing() throws Exception {
|
||||
dataSource = new DelegatingDataSourceWithWrapper();
|
||||
EasyMock.replay(delegate);
|
||||
assertThat(dataSource.unwrap(ExampleWrapper.class),
|
||||
is((ExampleWrapper) dataSource));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateIsWrapperForWithoutImplementing() throws Exception {
|
||||
EasyMock.expect(delegate.isWrapperFor(ExampleWrapper.class)).andReturn(true);
|
||||
EasyMock.replay(delegate);
|
||||
given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true);
|
||||
assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDelegateIsWrapperForImplementing() throws Exception {
|
||||
dataSource = new DelegatingDataSourceWithWrapper();
|
||||
EasyMock.replay(delegate);
|
||||
assertThat(dataSource.isWrapperFor(ExampleWrapper.class), is(true));
|
||||
EasyMock.verify(delegate);
|
||||
}
|
||||
|
||||
public static interface ExampleWrapper {
|
||||
|
||||
@@ -16,34 +16,34 @@
|
||||
|
||||
package org.springframework.jdbc.datasource;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class DriverManagerDataSourceTests extends TestCase {
|
||||
public class DriverManagerDataSourceTests {
|
||||
|
||||
private Connection connection = mock(Connection.class);
|
||||
|
||||
@Test
|
||||
public void testStandardUsage() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
final String uname = "uname";
|
||||
final String pwd = "pwd";
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
@Override
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
assertEquals(jdbcUrl, url);
|
||||
assertEquals(uname, props.getProperty("user"));
|
||||
assertEquals(pwd, props.getProperty("password"));
|
||||
return mockConnection;
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,15 +54,14 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
ds.setPassword(pwd);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
assertTrue(actualCon == connection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
assertTrue(ds.getPassword().equals(pwd));
|
||||
assertTrue(ds.getUsername().equals(uname));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUsageWithConnectionProperties() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
|
||||
@@ -72,11 +71,6 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
connProps.setProperty("user", "uname");
|
||||
connProps.setProperty("password", "pwd");
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
@Override
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
@@ -85,7 +79,7 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
assertEquals("pwd", props.getProperty("password"));
|
||||
assertEquals("myValue", props.getProperty("myProp"));
|
||||
assertEquals("yourValue", props.getProperty("yourProp"));
|
||||
return mockConnection;
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,13 +89,12 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
ds.setConnectionProperties(connProps);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
assertTrue(actualCon == connection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUsageWithConnectionPropertiesAndUserCredentials() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
final String uname = "uname";
|
||||
@@ -113,11 +106,6 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
connProps.setProperty("user", "uname2");
|
||||
connProps.setProperty("password", "pwd2");
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
@Override
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
@@ -126,7 +114,7 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
assertEquals(pwd, props.getProperty("password"));
|
||||
assertEquals("myValue", props.getProperty("myProp"));
|
||||
assertEquals("yourValue", props.getProperty("yourProp"));
|
||||
return mockConnection;
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,15 +126,14 @@ public class DriverManagerDataSourceTests extends TestCase {
|
||||
ds.setConnectionProperties(connProps);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
assertTrue(actualCon == connection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
assertTrue(ds.getPassword().equals(pwd));
|
||||
assertTrue(ds.getUsername().equals(uname));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidClassName() throws Exception {
|
||||
String bogusClassName = "foobar";
|
||||
DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
|
||||
@@ -16,68 +16,58 @@
|
||||
|
||||
package org.springframework.jdbc.datasource;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 28.05.2004
|
||||
*/
|
||||
public class UserCredentialsDataSourceAdapterTests extends TestCase {
|
||||
public class UserCredentialsDataSourceAdapterTests {
|
||||
|
||||
@Test
|
||||
public void testStaticCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection("user", "pw");
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
given(dataSource.getConnection("user", "pw")).willReturn(connection);
|
||||
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
adapter.setTargetDataSource(dataSource);
|
||||
adapter.setUsername("user");
|
||||
adapter.setPassword("pw");
|
||||
assertEquals(con, adapter.getConnection());
|
||||
assertEquals(connection, adapter.getConnection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
assertEquals(con, adapter.getConnection());
|
||||
adapter.setTargetDataSource(dataSource);
|
||||
assertEquals(connection, adapter.getConnection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testThreadBoundCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection("user", "pw");
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
given(dataSource.getConnection("user", "pw")).willReturn(connection);
|
||||
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
adapter.setTargetDataSource(dataSource);
|
||||
|
||||
adapter.setCredentialsForCurrentThread("user", "pw");
|
||||
try {
|
||||
assertEquals(con, adapter.getConnection());
|
||||
assertEquals(connection, adapter.getConnection());
|
||||
}
|
||||
finally {
|
||||
adapter.removeCredentialsFromCurrentThread();
|
||||
|
||||
@@ -17,15 +17,14 @@
|
||||
package org.springframework.jdbc.datasource.init;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.core.io.ClassRelativeResourceLoader;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceUtils;
|
||||
@@ -257,15 +256,9 @@ public class DatabasePopulatorTests {
|
||||
public void usesBoundConnectionIfAvailable() throws SQLException {
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
Connection connection = DataSourceUtils.getConnection(db);
|
||||
|
||||
DatabasePopulator populator = EasyMock.createMock(DatabasePopulator.class);
|
||||
populator.populate(connection);
|
||||
EasyMock.expectLastCall();
|
||||
EasyMock.replay(populator);
|
||||
|
||||
DatabasePopulator populator = mock(DatabasePopulator.class);
|
||||
DatabasePopulatorUtils.execute(populator, db);
|
||||
|
||||
EasyMock.verify(populator);
|
||||
verify(populator).populate(connection);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,8 +16,11 @@
|
||||
|
||||
package org.springframework.jdbc.datasource.lookup;
|
||||
|
||||
import static org.easymock.EasyMock.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@@ -37,12 +40,10 @@ public class BeanFactoryDataSourceLookupTests {
|
||||
|
||||
@Test
|
||||
public void testLookupSunnyDay() {
|
||||
BeanFactory beanFactory = createMock(BeanFactory.class);
|
||||
BeanFactory beanFactory = mock(BeanFactory.class);
|
||||
|
||||
StubDataSource expectedDataSource = new StubDataSource();
|
||||
expect(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).andReturn(expectedDataSource);
|
||||
|
||||
replay(beanFactory);
|
||||
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willReturn(expectedDataSource);
|
||||
|
||||
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
|
||||
lookup.setBeanFactory(beanFactory);
|
||||
@@ -50,27 +51,21 @@ public class BeanFactoryDataSourceLookupTests {
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from " +
|
||||
"getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
|
||||
verify(beanFactory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
|
||||
final BeanFactory beanFactory = createMock(BeanFactory.class);
|
||||
final BeanFactory beanFactory = mock(BeanFactory.class);
|
||||
|
||||
expect(
|
||||
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)
|
||||
).andThrow(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
|
||||
|
||||
replay(beanFactory);
|
||||
given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willThrow(
|
||||
new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME,
|
||||
DataSource.class, String.class));
|
||||
|
||||
try {
|
||||
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
|
||||
lookup.getDataSource(DATASOURCE_BEAN_NAME);
|
||||
fail("should have thrown DataSourceLookupFailureException");
|
||||
} catch (DataSourceLookupFailureException ex) { /* expected */ }
|
||||
|
||||
verify(beanFactory);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalStateException.class)
|
||||
|
||||
@@ -16,30 +16,35 @@
|
||||
|
||||
package org.springframework.jdbc.object;
|
||||
|
||||
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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Types;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 22.02.2005
|
||||
*/
|
||||
public class BatchSqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
public class BatchSqlUpdateTests {
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithExplicitFlush() throws Exception {
|
||||
doTestBatchUpdate(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBatchUpdateWithFlushThroughBatchSize() throws Exception {
|
||||
doTestBatchUpdate(true);
|
||||
}
|
||||
@@ -49,42 +54,19 @@ public class BatchSqlUpdateTests extends AbstractJdbcTests {
|
||||
final int[] ids = new int[] { 100, 200 };
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
mockPreparedStatement.getConnection();
|
||||
ctrlPreparedStatement.setReturnValue(mockConnection);
|
||||
mockPreparedStatement.setObject(1, new Integer(ids[0]), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.addBatch();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(1, new Integer(ids[1]), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.addBatch();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeBatch();
|
||||
ctrlPreparedStatement.setReturnValue(rowsAffected);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
Connection connection = mock(Connection.class);
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
PreparedStatement preparedStatement = mock(PreparedStatement.class);
|
||||
given(preparedStatement.getConnection()).willReturn(connection);
|
||||
given(preparedStatement.executeBatch()).willReturn(rowsAffected);
|
||||
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
mockDatabaseMetaData.supportsBatchUpdates();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
DatabaseMetaData mockDatabaseMetaData = mock(DatabaseMetaData.class);
|
||||
given(mockDatabaseMetaData.supportsBatchUpdates()).willReturn(true);
|
||||
given(connection.prepareStatement(sql)).willReturn(preparedStatement);
|
||||
given(connection.getMetaData()).willReturn(mockDatabaseMetaData);
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(mockDatabaseMetaData, 1);
|
||||
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlDatabaseMetaData.replay();
|
||||
replay();
|
||||
|
||||
BatchSqlUpdate update = new BatchSqlUpdate(mockDataSource, sql);
|
||||
BatchSqlUpdate update = new BatchSqlUpdate(dataSource, sql);
|
||||
update.declareParameter(new SqlParameter(Types.INTEGER));
|
||||
if (flushThroughBatchSize) {
|
||||
update.setBatchSize(2);
|
||||
@@ -122,8 +104,9 @@ public class BatchSqlUpdateTests extends AbstractJdbcTests {
|
||||
update.reset();
|
||||
assertEquals(0, update.getRowsAffected().length);
|
||||
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
verify(preparedStatement).setObject(1, new Integer(ids[0]), Types.INTEGER);
|
||||
verify(preparedStatement).setObject(1, new Integer(ids[1]), Types.INTEGER);
|
||||
verify(preparedStatement, times(2)).addBatch();
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,10 +16,13 @@
|
||||
|
||||
package org.springframework.jdbc.object;
|
||||
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
|
||||
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.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
@@ -28,119 +31,85 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.junit.runner.RunWith;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.Customer;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.jdbc.Customer;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class GenericSqlQueryTests extends AbstractJdbcTests {
|
||||
public class GenericSqlQueryTests {
|
||||
|
||||
private static final String SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED =
|
||||
"select id, forename from custmr where id = ? and country = ?";
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private ResultSet mockResultSet;
|
||||
private Connection connection;
|
||||
|
||||
private BeanFactory bf;
|
||||
private PreparedStatement preparedStatement;
|
||||
|
||||
private ResultSet resultSet;
|
||||
|
||||
@Override
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockPreparedStatement = createMock(PreparedStatement.class);
|
||||
mockResultSet = createMock(ResultSet.class);
|
||||
this.bf = new XmlBeanFactory(
|
||||
this.beanFactory = new XmlBeanFactory(
|
||||
new ClassPathResource("org/springframework/jdbc/object/GenericSqlQueryTests-context.xml"));
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
|
||||
testDataSource.setTarget(mockDataSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
EasyMock.verify(mockPreparedStatement);
|
||||
EasyMock.verify(mockResultSet);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
EasyMock.replay(mockPreparedStatement);
|
||||
EasyMock.replay(mockResultSet);
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
this.connection = mock(Connection.class);
|
||||
this.preparedStatement = mock(PreparedStatement.class);
|
||||
this.resultSet = mock(ResultSet.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) beanFactory.getBean("dataSource");
|
||||
testDataSource.setTarget(dataSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPlaceHoldersCustomerQuery() throws SQLException {
|
||||
SqlQuery query = (SqlQuery) bf.getBean("queryWithPlaceHolders");
|
||||
testCustomerQuery(query, false);
|
||||
SqlQuery query = (SqlQuery) beanFactory.getBean("queryWithPlaceHolders");
|
||||
doTestCustomerQuery(query, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNamedParameterCustomerQuery() throws SQLException {
|
||||
SqlQuery query = (SqlQuery) bf.getBean("queryWithNamedParameters");
|
||||
testCustomerQuery(query, true);
|
||||
SqlQuery query = (SqlQuery) beanFactory.getBean("queryWithNamedParameters");
|
||||
doTestCustomerQuery(query, true);
|
||||
}
|
||||
|
||||
private void testCustomerQuery(SqlQuery query, boolean namedParameters) throws SQLException {
|
||||
expect(mockResultSet.next()).andReturn(true);
|
||||
expect(mockResultSet.getInt("id")).andReturn(1);
|
||||
expect(mockResultSet.getString("forename")).andReturn("rod");
|
||||
expect(mockResultSet.next()).andReturn(false);
|
||||
mockResultSet.close();
|
||||
expectLastCall();
|
||||
private void doTestCustomerQuery(SqlQuery query, boolean namedParameters) throws SQLException {
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getInt("id")).willReturn(1);
|
||||
given(resultSet.getString("forename")).willReturn("rod");
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(preparedStatement.executeQuery()).willReturn(resultSet);
|
||||
given(connection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED)).willReturn(preparedStatement);
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
expectLastCall();
|
||||
expect(mockPreparedStatement.executeQuery()).andReturn(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
expect(mockPreparedStatement.getWarnings()).andReturn(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
expectLastCall();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
List l;
|
||||
List queryResults;
|
||||
if (namedParameters) {
|
||||
Map<String, Object> params = new HashMap<String, Object>(2);
|
||||
params.put("id", new Integer(1));
|
||||
params.put("country", "UK");
|
||||
l = query.executeByNamedParam(params);
|
||||
queryResults = query.executeByNamedParam(params);
|
||||
}
|
||||
else {
|
||||
Object[] params = new Object[] {new Integer(1), "UK"};
|
||||
l = query.execute(params);
|
||||
queryResults = query.execute(params);
|
||||
}
|
||||
assertTrue("Customer was returned correctly", l.size() == 1);
|
||||
Customer cust = (Customer) l.get(0);
|
||||
assertTrue("Customer was returned correctly", queryResults.size() == 1);
|
||||
Customer cust = (Customer) queryResults.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
|
||||
verify(resultSet).close();
|
||||
verify(preparedStatement).setObject(1, new Integer(1), Types.INTEGER);
|
||||
verify(preparedStatement).setString(2, "UK");
|
||||
verify(preparedStatement).close();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,104 +16,63 @@
|
||||
|
||||
package org.springframework.jdbc.object;
|
||||
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class GenericStoredProcedureTests extends AbstractJdbcTests {
|
||||
public class GenericStoredProcedureTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private CallableStatement mockCallable;
|
||||
|
||||
private BeanFactory bf;
|
||||
|
||||
@Override
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockCallable = createMock(CallableStatement.class);
|
||||
bf = new XmlBeanFactory(
|
||||
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
|
||||
testDataSource.setTarget(mockDataSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
EasyMock.verify(mockCallable);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
EasyMock.replay(mockCallable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoices() throws Exception {
|
||||
BeanFactory bf = new XmlBeanFactory(
|
||||
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));
|
||||
Connection connection = mock(Connection.class);
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
CallableStatement callableStatement = mock(CallableStatement.class);
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
|
||||
testDataSource.setTarget(dataSource);
|
||||
|
||||
mockCallable.setObject(1, new Integer(1106), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockCallable.setObject(2, new Integer(3), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockCallable.registerOutParameter(3, Types.INTEGER);
|
||||
expectLastCall();
|
||||
expect(mockCallable.execute()).andReturn(false);
|
||||
expect(mockCallable.getUpdateCount()).andReturn(-1);
|
||||
expect(mockCallable.getObject(3)).andReturn(new Integer(4));
|
||||
if (debugEnabled) {
|
||||
expect(mockCallable.getWarnings()).andReturn(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
expectLastCall();
|
||||
given(callableStatement.execute()).willReturn(false);
|
||||
given(callableStatement.getUpdateCount()).willReturn(-1);
|
||||
given(callableStatement.getObject(3)).willReturn(new Integer(4));
|
||||
|
||||
mockConnection.prepareCall("{call " + "add_invoice" + "(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
|
||||
replay();
|
||||
|
||||
testAddInvoice(1106, 3);
|
||||
}
|
||||
|
||||
private void testAddInvoice(final int amount, final int custid)
|
||||
throws Exception {
|
||||
given(connection.prepareCall("{call " + "add_invoice" + "(?, ?, ?)}")).willReturn(callableStatement);
|
||||
|
||||
StoredProcedure adder = (StoredProcedure) bf.getBean("genericProcedure");
|
||||
Map<String, Object> in = new HashMap<String, Object>(2);
|
||||
in.put("amount", amount);
|
||||
in.put("custid", custid);
|
||||
in.put("amount", 1106);
|
||||
in.put("custid", 3);
|
||||
Map out = adder.execute(in);
|
||||
Integer id = (Integer) out.get("newid");
|
||||
assertEquals(4, id.intValue());
|
||||
|
||||
verify(callableStatement).setObject(1, new Integer(1106), Types.INTEGER);
|
||||
verify(callableStatement).setObject(2, new Integer(3), Types.INTEGER);
|
||||
verify(callableStatement).registerOutParameter(3, Types.INTEGER);
|
||||
verify(callableStatement).close();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,12 @@
|
||||
|
||||
package org.springframework.jdbc.object;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
@@ -24,13 +30,15 @@ import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
|
||||
@@ -39,151 +47,103 @@ import org.springframework.jdbc.support.KeyHolder;
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
public class SqlUpdateTests {
|
||||
|
||||
private static final String UPDATE =
|
||||
"update seat_status set booking_id = null";
|
||||
"update seat_status set booking_id = null";
|
||||
private static final String UPDATE_INT =
|
||||
"update seat_status set booking_id = null where performance_id = ?";
|
||||
"update seat_status set booking_id = null where performance_id = ?";
|
||||
private static final String UPDATE_INT_INT =
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
|
||||
private static final String UPDATE_NAMED_PARAMETERS =
|
||||
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
|
||||
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
|
||||
private static final String UPDATE_STRING =
|
||||
"update seat_status set booking_id = null where name = ?";
|
||||
"update seat_status set booking_id = null where name = ?";
|
||||
private static final String UPDATE_OBJECTS =
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ? and name = ? and confirmed = ?";
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ? and name = ? and confirmed = ?";
|
||||
private static final String INSERT_GENERATE_KEYS =
|
||||
"insert into show (name) values(?)";
|
||||
"insert into show (name) values(?)";
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private MockControl ctrlResultSetMetaData;
|
||||
private ResultSetMetaData mockResultSetMetaData;
|
||||
private DataSource dataSource;
|
||||
private Connection connection;
|
||||
private PreparedStatement preparedStatement;
|
||||
private ResultSet resultSet;
|
||||
private ResultSetMetaData resultSetMetaData;
|
||||
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
dataSource = mock(DataSource.class);
|
||||
connection = mock(Connection.class);
|
||||
preparedStatement = mock(PreparedStatement.class);
|
||||
resultSet = mock(ResultSet.class);
|
||||
resultSetMetaData = mock(ResultSetMetaData.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
}
|
||||
@After
|
||||
public void verifyClosed() throws Exception {
|
||||
verify(preparedStatement).close();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testUpdate() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
|
||||
Updater pc = new Updater();
|
||||
int rowsAffected = pc.run();
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateInt() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_INT)).willReturn(preparedStatement);
|
||||
|
||||
IntUpdater pc = new IntUpdater();
|
||||
int rowsAffected = pc.run(1);
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateIntInt() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement);
|
||||
|
||||
IntIntUpdater pc = new IntIntUpdater();
|
||||
int rowsAffected = pc.run(1, 1);
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(2, 1, Types.NUMERIC);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNamedParameterUpdateWithUnnamedDeclarations() throws SQLException {
|
||||
doTestNamedParameterUpdate(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNamedParameterUpdateWithNamedDeclarations() throws SQLException {
|
||||
doTestNamedParameterUpdate(true);
|
||||
}
|
||||
|
||||
private void doTestNamedParameterUpdate(final boolean namedDeclarations) throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
private void doTestNamedParameterUpdate(final boolean namedDeclarations)
|
||||
throws SQLException {
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_INT_INT)).willReturn(preparedStatement);
|
||||
|
||||
class NamedParameterUpdater extends SqlUpdate {
|
||||
|
||||
public NamedParameterUpdater() {
|
||||
setSql(UPDATE_NAMED_PARAMETERS);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
if (namedDeclarations) {
|
||||
declareParameter(new SqlParameter("priceId", Types.DECIMAL));
|
||||
declareParameter(new SqlParameter("perfId", Types.NUMERIC));
|
||||
@@ -196,9 +156,9 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
}
|
||||
|
||||
public int run(int performanceId, int type) {
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(performanceId));
|
||||
params.put("priceId", new Integer(type));
|
||||
Map<String, Integer> params = new HashMap<String, Integer>();
|
||||
params.put("perfId", performanceId);
|
||||
params.put("priceId", type);
|
||||
return updateByNamedParam(params);
|
||||
}
|
||||
}
|
||||
@@ -206,245 +166,134 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
NamedParameterUpdater pc = new NamedParameterUpdater();
|
||||
int rowsAffected = pc.run(1, 1);
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(2, 1, Types.DECIMAL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateString() throws SQLException {
|
||||
mockPreparedStatement.setString(1, "rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_STRING);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_STRING)).willReturn(preparedStatement);
|
||||
|
||||
StringUpdater pc = new StringUpdater();
|
||||
int rowsAffected = pc.run("rod");
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setString(1, "rod");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateMixed() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC, 2);
|
||||
mockPreparedStatement.setString(3, "rod");
|
||||
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_OBJECTS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
|
||||
|
||||
MixedUpdater pc = new MixedUpdater();
|
||||
int rowsAffected = pc.run(1, 1, "rod", true);
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(2, 1, Types.NUMERIC, 2);
|
||||
verify(preparedStatement).setString(3, "rod");
|
||||
verify(preparedStatement).setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateAndGeneratedKeys() throws SQLException {
|
||||
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
|
||||
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("1", 2);
|
||||
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setString(1, "rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
mockPreparedStatement.getGeneratedKeys();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(INSERT_GENERATE_KEYS, PreparedStatement.RETURN_GENERATED_KEYS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
ctrlResultSet.replay();
|
||||
ctrlResultSetMetaData.replay();
|
||||
given(resultSetMetaData.getColumnCount()).willReturn(1);
|
||||
given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
|
||||
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
|
||||
given(resultSet.next()).willReturn(true, false);
|
||||
given(resultSet.getObject(1)).willReturn(11);
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(preparedStatement.getGeneratedKeys()).willReturn(resultSet);
|
||||
given(connection.prepareStatement(INSERT_GENERATE_KEYS,
|
||||
PreparedStatement.RETURN_GENERATED_KEYS)
|
||||
).willReturn(preparedStatement);
|
||||
|
||||
GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
|
||||
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
|
||||
int rowsAffected = pc.run("rod", generatedKeyHolder);
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
assertEquals(1, generatedKeyHolder.getKeyList().size());
|
||||
assertEquals(11, generatedKeyHolder.getKey().intValue());
|
||||
verify(preparedStatement).setString(1, "rod");
|
||||
verify(resultSet).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateConstructor() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setString(3, "rod");
|
||||
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_OBJECTS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
given(preparedStatement.executeUpdate()).willReturn(1);
|
||||
given(connection.prepareStatement(UPDATE_OBJECTS)).willReturn(preparedStatement);
|
||||
ConstructorUpdater pc = new ConstructorUpdater();
|
||||
|
||||
int rowsAffected = pc.run(1, 1, "rod", true);
|
||||
|
||||
assertEquals(1, rowsAffected);
|
||||
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
|
||||
verify(preparedStatement).setObject(2, 1, Types.NUMERIC);
|
||||
verify(preparedStatement).setString(3, "rod");
|
||||
verify(preparedStatement).setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnderMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(3);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(3);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
|
||||
int rowsAffected = pc.run();
|
||||
assertEquals(3, rowsAffected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(5);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(5);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
int rowsAffected = pc.run();
|
||||
|
||||
assertEquals(5, rowsAffected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOverMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(8);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(8);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
try {
|
||||
int rowsAffected = pc.run();
|
||||
fail("Shouldn't continue when too many rows affected");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
|
||||
// OK
|
||||
}
|
||||
|
||||
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
|
||||
pc.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(3);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
given(preparedStatement.executeUpdate()).willReturn(3);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
|
||||
RequiredRowsUpdater pc = new RequiredRowsUpdater();
|
||||
int rowsAffected = pc.run();
|
||||
|
||||
assertEquals(3, rowsAffected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotRequiredRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(2);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
given(preparedStatement.executeUpdate()).willReturn(2);
|
||||
given(connection.prepareStatement(UPDATE)).willReturn(preparedStatement);
|
||||
thrown.expect(JdbcUpdateAffectedIncorrectNumberOfRowsException.class);
|
||||
RequiredRowsUpdater pc = new RequiredRowsUpdater();
|
||||
try {
|
||||
int rowsAffected = pc.run();
|
||||
fail("Shouldn't continue when too many rows affected");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
|
||||
// OK
|
||||
}
|
||||
pc.run();
|
||||
}
|
||||
|
||||
|
||||
private class Updater extends SqlUpdate {
|
||||
|
||||
public Updater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
compile();
|
||||
}
|
||||
|
||||
@@ -458,7 +307,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public IntUpdater() {
|
||||
setSql(UPDATE_INT);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
compile();
|
||||
}
|
||||
@@ -473,7 +322,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public IntIntUpdater() {
|
||||
setSql(UPDATE_INT_INT);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
compile();
|
||||
@@ -489,7 +338,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public StringUpdater() {
|
||||
setSql(UPDATE_STRING);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
compile();
|
||||
}
|
||||
@@ -504,7 +353,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public MixedUpdater() {
|
||||
setSql(UPDATE_OBJECTS);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
declareParameter(new SqlParameter(Types.NUMERIC, 2));
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
@@ -514,7 +363,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public int run(int performanceId, int type, String name, boolean confirmed) {
|
||||
Object[] params =
|
||||
new Object[] {new Integer(performanceId), new Integer(type), name,
|
||||
new Object[] {performanceId, type, name,
|
||||
new Boolean(confirmed)};
|
||||
return update(params);
|
||||
}
|
||||
@@ -525,7 +374,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public GeneratedKeysUpdater() {
|
||||
setSql(INSERT_GENERATE_KEYS);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
setReturnGeneratedKeys(true);
|
||||
compile();
|
||||
@@ -541,7 +390,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
private class ConstructorUpdater extends SqlUpdate {
|
||||
|
||||
public ConstructorUpdater() {
|
||||
super(mockDataSource, UPDATE_OBJECTS,
|
||||
super(dataSource, UPDATE_OBJECTS,
|
||||
new int[] {Types.NUMERIC, Types.NUMERIC, Types.VARCHAR, Types.BOOLEAN });
|
||||
compile();
|
||||
}
|
||||
@@ -549,7 +398,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
public int run(int performanceId, int type, String name, boolean confirmed) {
|
||||
Object[] params =
|
||||
new Object[] {
|
||||
new Integer(performanceId), new Integer(type), name, new Boolean(confirmed)};
|
||||
performanceId, type, name, new Boolean(confirmed)};
|
||||
return update(params);
|
||||
}
|
||||
}
|
||||
@@ -559,7 +408,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public MaxRowsUpdater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
setMaxRowsAffected(5);
|
||||
compile();
|
||||
}
|
||||
@@ -574,7 +423,7 @@ public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
public RequiredRowsUpdater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
setDataSource(dataSource);
|
||||
setRequiredRowsAffected(3);
|
||||
compile();
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,12 @@
|
||||
|
||||
package org.springframework.jdbc.support;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
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 java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
@@ -23,9 +29,7 @@ import java.sql.Statement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
|
||||
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
|
||||
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
|
||||
@@ -35,50 +39,26 @@ import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIn
|
||||
* @author Juergen Hoeller
|
||||
* @since 27.02.2004
|
||||
*/
|
||||
public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
public class DataFieldMaxValueIncrementerTests {
|
||||
|
||||
private DataSource dataSource = mock(DataSource.class);
|
||||
private Connection connection = mock(Connection.class);
|
||||
private Statement statement = mock(Statement.class);
|
||||
private ResultSet resultSet = mock(ResultSet.class);
|
||||
|
||||
@Test
|
||||
public void testHsqlMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeUpdate("insert into myseq values(null)");
|
||||
stmtControl.setReturnValue(1, 6);
|
||||
stmt.executeQuery("select max(identity()) from myseq");
|
||||
stmtControl.setReturnValue(rs, 6);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 6);
|
||||
for (long i = 0; i < 6; i++) {
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(i);
|
||||
}
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(6);
|
||||
stmt.executeUpdate("delete from myseq where seq < 2");
|
||||
stmtControl.setReturnValue(1);
|
||||
stmt.executeUpdate("delete from myseq where seq < 5");
|
||||
stmtControl.setReturnValue(1);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
given(statement.executeUpdate("insert into myseq values(null)")).willReturn(1);
|
||||
given(statement.executeQuery("select max(identity()) from myseq")).willReturn(resultSet);
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getLong(1)).willReturn(0L, 1L, 2L, 3L, 4L, 5L);
|
||||
given(statement.executeUpdate("delete from myseq where seq < 2")).willReturn(1);
|
||||
given(statement.executeUpdate("delete from myseq where seq < 5")).willReturn(1);
|
||||
|
||||
HsqlMaxValueIncrementer incrementer = new HsqlMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setDataSource(dataSource);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setColumnName("seq");
|
||||
incrementer.setCacheSize(3);
|
||||
@@ -90,51 +70,22 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
assertEquals("002", incrementer.nextStringValue());
|
||||
assertEquals(3, incrementer.nextIntValue());
|
||||
assertEquals(4, incrementer.nextLongValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
verify(resultSet, times(6)).close();
|
||||
verify(statement, times(2)).close();
|
||||
verify(connection, times(2)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMySQLMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeUpdate("update myseq set seq = last_insert_id(seq + 2)");
|
||||
stmtControl.setReturnValue(1, 2);
|
||||
stmt.executeQuery("select last_insert_id()");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(4);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
given(statement.executeUpdate("update myseq set seq = last_insert_id(seq + 2)")).willReturn(1);
|
||||
given(statement.executeQuery("select last_insert_id()")).willReturn(resultSet);
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getLong(1)).willReturn(2L, 4L);
|
||||
|
||||
MySQLMaxValueIncrementer incrementer = new MySQLMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setDataSource(dataSource);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setColumnName("seq");
|
||||
incrementer.setCacheSize(2);
|
||||
@@ -146,48 +97,21 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
assertEquals("3", incrementer.nextStringValue());
|
||||
assertEquals(4, incrementer.nextLongValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
verify(resultSet, times(2)).close();
|
||||
verify(statement, times(2)).close();
|
||||
verify(connection, times(2)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostgreSQLSequenceMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeQuery("select nextval('myseq')");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(10);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(12);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
given(statement.executeQuery("select nextval('myseq')")).willReturn(resultSet);
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getLong(1)).willReturn(10L, 12L);
|
||||
|
||||
PostgreSQLSequenceMaxValueIncrementer incrementer = new PostgreSQLSequenceMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setDataSource(dataSource);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setPaddingLength(5);
|
||||
incrementer.afterPropertiesSet();
|
||||
@@ -195,48 +119,21 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
assertEquals("00010", incrementer.nextStringValue());
|
||||
assertEquals(12, incrementer.nextIntValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
verify(resultSet, times(2)).close();
|
||||
verify(statement, times(2)).close();
|
||||
verify(connection, times(2)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOracleSequenceMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeQuery("select myseq.nextval from dual");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(10);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(12);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
given(connection.createStatement()).willReturn(statement);
|
||||
given(statement.executeQuery("select myseq.nextval from dual")).willReturn(resultSet);
|
||||
given(resultSet.next()).willReturn(true);
|
||||
given(resultSet.getLong(1)).willReturn(10L, 12L);
|
||||
|
||||
OracleSequenceMaxValueIncrementer incrementer = new OracleSequenceMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setDataSource(dataSource);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setPaddingLength(2);
|
||||
incrementer.afterPropertiesSet();
|
||||
@@ -244,10 +141,9 @@ public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
assertEquals(10, incrementer.nextLongValue());
|
||||
assertEquals("12", incrementer.nextStringValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
verify(resultSet, times(2)).close();
|
||||
verify(statement, times(2)).close();
|
||||
verify(connection, times(2)).close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,18 +16,19 @@
|
||||
|
||||
package org.springframework.jdbc.support;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.support.lob.DefaultLobHandler;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
@@ -36,126 +37,77 @@ import org.springframework.jdbc.support.lob.LobHandler;
|
||||
* @author Juergen Hoeller
|
||||
* @since 17.12.2003
|
||||
*/
|
||||
public class DefaultLobHandlerTests extends TestCase {
|
||||
public class DefaultLobHandlerTests {
|
||||
|
||||
private ResultSet rs = mock(ResultSet.class);
|
||||
private PreparedStatement ps = mock(PreparedStatement.class);
|
||||
private LobHandler lobHandler = new DefaultLobHandler();
|
||||
private LobCreator lobCreator = lobHandler.getLobCreator();
|
||||
|
||||
@Test
|
||||
public void testGetBlobAsBytes() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getBytes(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getBlobAsBytes(rs, 1);
|
||||
rsControl.verify();
|
||||
verify(rs).getBytes(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBlobAsBinaryStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getBinaryStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getBlobAsBinaryStream(rs, 1);
|
||||
rsControl.verify();
|
||||
verify(rs).getBinaryStream(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetClobAsString() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsString(rs, 1);
|
||||
rsControl.verify();
|
||||
verify(rs).getString(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetClobAsAsciiStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getAsciiStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsAsciiStream(rs, 1);
|
||||
rsControl.verify();
|
||||
verify(rs).getAsciiStream(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetClobAsCharacterStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getCharacterStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsCharacterStream(rs, 1);
|
||||
rsControl.verify();
|
||||
verify(rs).getCharacterStream(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetBlobAsBytes() throws SQLException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
byte[] content = "testContent".getBytes();
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setBytes(1, content);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
psControl.verify();
|
||||
verify(ps).setBytes(1, content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetBlobAsBinaryStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
|
||||
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setBinaryStream(1, bis, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11);
|
||||
psControl.verify();
|
||||
verify(ps).setBinaryStream(1, bis, 11);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetClobAsString() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
String content = "testContent";
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setString(1, content);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsString(ps, 1, content);
|
||||
psControl.verify();
|
||||
verify(ps).setString(1, content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetClobAsAsciiStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setAsciiStream(1, bis, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsAsciiStream(ps, 1, bis, 11);
|
||||
psControl.verify();
|
||||
verify(ps).setAsciiStream(1, bis, 11);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetClobAsCharacterStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
Reader str = new StringReader("testContent");
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setCharacterStream(1, str, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsCharacterStream(ps, 1, str, 11);
|
||||
psControl.verify();
|
||||
verify(ps).setCharacterStream(1, str, 11);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
|
||||
package org.springframework.jdbc.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
@@ -24,9 +28,7 @@ import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor;
|
||||
import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
|
||||
|
||||
@@ -34,33 +36,23 @@ import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
|
||||
* @author Andre Biryukov
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class NativeJdbcExtractorTests extends TestCase {
|
||||
public class NativeJdbcExtractorTests {
|
||||
|
||||
@Test
|
||||
public void testSimpleNativeJdbcExtractor() throws SQLException {
|
||||
SimpleNativeJdbcExtractor extractor = new SimpleNativeJdbcExtractor();
|
||||
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl dbmdControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData dbmd = (DatabaseMetaData) dbmdControl.getMock();
|
||||
MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
Connection con2 = (Connection) con2Control.getMock();
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(dbmd, 2);
|
||||
dbmd.getConnection();
|
||||
dbmdControl.setReturnValue(con2, 2);
|
||||
conControl.replay();
|
||||
dbmdControl.replay();
|
||||
con2Control.replay();
|
||||
Connection con = mock(Connection.class);
|
||||
DatabaseMetaData dbmd = mock(DatabaseMetaData.class);
|
||||
Connection con2 = mock(Connection.class);
|
||||
given(con.getMetaData()).willReturn(dbmd);
|
||||
given(dbmd.getConnection()).willReturn(con2);
|
||||
|
||||
Connection nativeCon = extractor.getNativeConnection(con);
|
||||
assertEquals(con2, nativeCon);
|
||||
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
stmt.getConnection();
|
||||
stmtControl.setReturnValue(con);
|
||||
stmtControl.replay();
|
||||
Statement stmt = mock(Statement.class);
|
||||
given(stmt.getConnection()).willReturn(con);
|
||||
|
||||
nativeCon = extractor.getNativeConnectionFromStatement(stmt);
|
||||
assertEquals(con2, nativeCon);
|
||||
@@ -68,51 +60,29 @@ public class NativeJdbcExtractorTests extends TestCase {
|
||||
Statement nativeStmt = extractor.getNativeStatement(stmt);
|
||||
assertEquals(nativeStmt, stmt);
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
psControl.replay();
|
||||
PreparedStatement ps = mock(PreparedStatement.class);
|
||||
|
||||
PreparedStatement nativePs = extractor.getNativePreparedStatement(ps);
|
||||
assertEquals(ps, nativePs);
|
||||
|
||||
MockControl csControl = MockControl.createControl(CallableStatement.class);
|
||||
CallableStatement cs = (CallableStatement) csControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
cs.getResultSet();
|
||||
csControl.setReturnValue(rs);
|
||||
csControl.replay();
|
||||
rsControl.replay();
|
||||
CallableStatement cs = mock(CallableStatement.class);
|
||||
ResultSet rs = mock(ResultSet.class);
|
||||
given(cs.getResultSet()).willReturn(rs);
|
||||
|
||||
CallableStatement nativeCs = extractor.getNativeCallableStatement(cs);
|
||||
assertEquals(cs, nativeCs);
|
||||
|
||||
ResultSet nativeRs = extractor.getNativeResultSet(cs.getResultSet());
|
||||
assertEquals(nativeRs, rs);
|
||||
|
||||
conControl.verify();
|
||||
dbmdControl.verify();
|
||||
con2Control.verify();
|
||||
stmtControl.verify();
|
||||
psControl.verify();
|
||||
csControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testCommonsDbcpNativeJdbcExtractor() throws SQLException {
|
||||
CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
|
||||
assertFalse(extractor.isNativeConnectionNecessaryForNativeStatements());
|
||||
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(null, 2);
|
||||
stmt.getConnection();
|
||||
stmtControl.setReturnValue(con, 1);
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
Connection con = mock(Connection.class);
|
||||
Statement stmt = mock(Statement.class);
|
||||
given(stmt.getConnection()).willReturn(con);
|
||||
|
||||
Connection nativeConnection = extractor.getNativeConnection(con);
|
||||
assertEquals(con, nativeConnection);
|
||||
@@ -121,24 +91,14 @@ public class NativeJdbcExtractorTests extends TestCase {
|
||||
assertEquals(con, nativeConnection);
|
||||
assertEquals(stmt, extractor.getNativeStatement(stmt));
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
psControl.replay();
|
||||
PreparedStatement ps = mock(PreparedStatement.class);
|
||||
assertEquals(ps, extractor.getNativePreparedStatement(ps));
|
||||
|
||||
MockControl csControl = MockControl.createControl(CallableStatement.class);
|
||||
CallableStatement cs = (CallableStatement) csControl.getMock();
|
||||
csControl.replay();
|
||||
CallableStatement cs = mock(CallableStatement.class);
|
||||
assertEquals(cs, extractor.getNativePreparedStatement(cs));
|
||||
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rsControl.replay();
|
||||
ResultSet rs = mock(ResultSet.class);
|
||||
assertEquals(rs, extractor.getNativeResultSet(rs));
|
||||
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,6 +16,16 @@
|
||||
|
||||
package org.springframework.jdbc.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThat;
|
||||
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.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
@@ -23,26 +33,22 @@ import java.util.Arrays;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Tests for SQLErrorCodes loading.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
public class SQLErrorCodesFactoryTests {
|
||||
|
||||
/**
|
||||
* Check that a default instance returns empty error codes for an unknown database.
|
||||
*/
|
||||
@Test
|
||||
public void testDefaultInstanceWithNoSuchDatabase() {
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx");
|
||||
assertTrue(sec.getBadSqlGrammarCodes().length == 0);
|
||||
@@ -52,6 +58,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
/**
|
||||
* Check that a known database produces recognizable codes.
|
||||
*/
|
||||
@Test
|
||||
public void testDefaultInstanceWithOracle() {
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("Oracle");
|
||||
assertIsOracle(sec);
|
||||
@@ -119,6 +126,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupOrder() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
private int lookups = 0;
|
||||
@@ -147,6 +155,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
/**
|
||||
* Check that user defined error codes take precedence.
|
||||
*/
|
||||
@Test
|
||||
public void testFindUserDefinedCodes() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
@Override
|
||||
@@ -166,6 +175,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidUserDefinedCodeFormat() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
@Override
|
||||
@@ -187,6 +197,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
/**
|
||||
* Check that custom error codes take precedence.
|
||||
*/
|
||||
@Test
|
||||
public void testFindCustomCodes() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
@Override
|
||||
@@ -207,43 +218,27 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
assertEquals(1, translation.getErrorCodes().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDataSourceWithNullMetadata() throws Exception {
|
||||
Connection connection = mock(Connection.class);
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(null);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setVoidCallable();
|
||||
ctrlConnection.replay();
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
ctrlDataSource.replay();
|
||||
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(dataSource);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
ctrlConnection.verify();
|
||||
ctrlDataSource.verify();
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFromDataSourceWithSQLException() throws Exception {
|
||||
|
||||
SQLException expectedSQLException = new SQLException();
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setThrowable(expectedSQLException);
|
||||
ctrlDataSource.replay();
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willThrow(expectedSQLException);
|
||||
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(dataSource);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
private void assertIsEmpty(SQLErrorCodes sec) {
|
||||
@@ -253,25 +248,14 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
}
|
||||
|
||||
private SQLErrorCodes getErrorCodesFromDataSource(String productName, SQLErrorCodesFactory factory) throws Exception {
|
||||
MockControl mdControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock();
|
||||
md.getDatabaseProductName();
|
||||
mdControl.setReturnValue(productName);
|
||||
mdControl.replay();
|
||||
DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
|
||||
given(databaseMetaData.getDatabaseProductName()).willReturn(productName);
|
||||
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(md);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setVoidCallable();
|
||||
ctrlConnection.replay();
|
||||
Connection connection = mock(Connection.class);
|
||||
given(connection.getMetaData()).willReturn(databaseMetaData);
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
ctrlDataSource.replay();
|
||||
DataSource dataSource = mock(DataSource.class);
|
||||
given(dataSource.getConnection()).willReturn(connection);
|
||||
|
||||
SQLErrorCodesFactory secf = null;
|
||||
if (factory != null) {
|
||||
@@ -281,33 +265,35 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
secf = SQLErrorCodesFactory.getInstance();
|
||||
}
|
||||
|
||||
SQLErrorCodes sec = secf.getErrorCodes(mockDataSource);
|
||||
SQLErrorCodes sec = secf.getErrorCodes(dataSource);
|
||||
|
||||
mdControl.verify();
|
||||
ctrlConnection.verify();
|
||||
ctrlDataSource.verify();
|
||||
|
||||
SQLErrorCodes sec2 = secf.getErrorCodes(mockDataSource);
|
||||
SQLErrorCodes sec2 = secf.getErrorCodes(dataSource);
|
||||
assertSame("Cached per DataSource", sec2, sec);
|
||||
|
||||
verify(connection).close();
|
||||
return sec;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSQLServerRecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("MS-SQL", null);
|
||||
assertIsSQLServer(sec);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOracleRecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("Oracle", null);
|
||||
assertIsOracle(sec);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHsqlRecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("HSQL Database Engine", null);
|
||||
assertIsHsql(sec);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDB2RecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", null);
|
||||
assertIsDB2(sec);
|
||||
@@ -320,6 +306,7 @@ public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
/**
|
||||
* Check that wild card database name works.
|
||||
*/
|
||||
@Test
|
||||
public void testWildCardNameRecognized() throws Exception {
|
||||
class WildcardSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
@Override
|
||||
|
||||
@@ -16,6 +16,11 @@
|
||||
|
||||
package org.springframework.jdbc.support.rowset;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigDecimal;
|
||||
@@ -25,156 +30,172 @@ import java.sql.SQLException;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.InvalidResultSetAccessException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class ResultSetWrappingRowSetTests extends TestCase {
|
||||
public class ResultSetWrappingRowSetTests {
|
||||
|
||||
private MockControl rsetControl;
|
||||
private ResultSet rset;
|
||||
private ResultSetWrappingSqlRowSet rowset;
|
||||
|
||||
@Override
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
rsetControl = MockControl.createControl(ResultSet.class);
|
||||
rset = (ResultSet) rsetControl.getMock();
|
||||
rset.getMetaData();
|
||||
rsetControl.setReturnValue(null);
|
||||
rset.getMetaData();
|
||||
rsetControl.setReturnValue(null);
|
||||
rset = mock(ResultSet.class);
|
||||
rowset = new ResultSetWrappingSqlRowSet(rset);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBigDecimalInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), BigDecimal.valueOf(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBigDecimalString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", BigDecimal.valueOf(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStringInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetStringString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", "test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTimestampInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Timestamp(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTimestampString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Timestamp(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDateInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Date(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDateString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Date(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTimeInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Time(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTimeString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Time(1234l));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetObjectInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetObjectString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIntInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Integer(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetIntString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Integer(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFloatInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Float(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFloatString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Float(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDoubleInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Double(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDoubleString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Double(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLongInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Long(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetLongString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Long(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBooleanInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Boolean(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBooleanString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {String.class});
|
||||
@@ -183,56 +204,14 @@ public class ResultSetWrappingRowSetTests extends TestCase {
|
||||
|
||||
private void doTest(Method rsetMethod, Method rowsetMethod, Object arg, Object ret) throws Exception {
|
||||
if (arg instanceof String) {
|
||||
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
|
||||
findMethod.invoke(rset, new Object[] {arg});
|
||||
rsetControl.setReturnValue(1);
|
||||
rsetMethod.invoke(rset, new Object[] {1});
|
||||
given(rset.findColumn((String) arg)).willReturn(1);
|
||||
given(rsetMethod.invoke(rset, 1)).willReturn(ret).willThrow(new SQLException("test"));
|
||||
} else {
|
||||
given(rsetMethod.invoke(rset, arg)).willReturn(ret).willThrow(new SQLException("test"));
|
||||
}
|
||||
else {
|
||||
rsetMethod.invoke(rset, new Object[] {arg});
|
||||
}
|
||||
if (ret instanceof Double) {
|
||||
rsetControl.setReturnValue(((Double) ret).doubleValue());
|
||||
}
|
||||
else if (ret instanceof Float) {
|
||||
rsetControl.setReturnValue(((Float) ret).floatValue());
|
||||
}
|
||||
else if (ret instanceof Integer) {
|
||||
rsetControl.setReturnValue(((Integer) ret).intValue());
|
||||
}
|
||||
else if (ret instanceof Short) {
|
||||
rsetControl.setReturnValue(((Short) ret).shortValue());
|
||||
}
|
||||
else if (ret instanceof Long) {
|
||||
rsetControl.setReturnValue(((Long) ret).longValue());
|
||||
}
|
||||
else if (ret instanceof Boolean) {
|
||||
rsetControl.setReturnValue(((Boolean) ret).booleanValue());
|
||||
}
|
||||
else if (ret instanceof Byte) {
|
||||
rsetControl.setReturnValue(((Byte) ret).byteValue());
|
||||
}
|
||||
else {
|
||||
rsetControl.setReturnValue(ret);
|
||||
}
|
||||
|
||||
if (arg instanceof String) {
|
||||
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
|
||||
findMethod.invoke(rset, new Object[] {arg});
|
||||
rsetControl.setReturnValue(1);
|
||||
rsetMethod.invoke(rset, new Object[] {1});
|
||||
}
|
||||
else {
|
||||
rsetMethod.invoke(rset, new Object[] {arg});
|
||||
}
|
||||
rsetControl.setThrowable(new SQLException("test"));
|
||||
|
||||
rsetControl.replay();
|
||||
|
||||
rowset = new ResultSetWrappingSqlRowSet(rset);
|
||||
rowsetMethod.invoke(rowset, new Object[] {arg});
|
||||
rowsetMethod.invoke(rowset, arg);
|
||||
try {
|
||||
rowsetMethod.invoke(rowset, new Object[] {arg});
|
||||
rowsetMethod.invoke(rowset, arg);
|
||||
fail("InvalidResultSetAccessException should have been thrown");
|
||||
}
|
||||
catch (InvocationTargetException ex) {
|
||||
|
||||
Reference in New Issue
Block a user