Rename modules {org.springframework.*=>spring-*}

This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.

Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example

    $ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history up until the renaming event, where

    $ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java

will show history for all changes to the file, before and after the
renaming.

See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
Chris Beams
2012-01-20 22:51:02 +01:00
parent b6cb514d38
commit 02a4473c62
5671 changed files with 20 additions and 32 deletions

View File

@@ -0,0 +1,37 @@
/*
* 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.beans;
import org.springframework.core.enums.ShortCodedLabeledEnum;
/**
* @author Rob Harrop
*/
@SuppressWarnings({ "serial", "deprecation" })
public class Colour extends ShortCodedLabeledEnum {
public static final Colour RED = new Colour(0, "RED");
public static final Colour BLUE = new Colour(1, "BLUE");
public static final Colour GREEN = new Colour(2, "GREEN");
public static final Colour PURPLE = new Colour(3, "PURPLE");
private Colour(int code, String label) {
super(code, label);
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.beans;
public class Employee extends TestBean {
private String co;
/**
* Constructor for Employee.
*/
public Employee() {
super();
}
public String getCompany() {
return co;
}
public void setCompany(String co) {
this.co = co;
}
}

View File

@@ -0,0 +1,23 @@
/*
* 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.beans;
public interface INestedTestBean {
public String getCompany();
}

View File

@@ -0,0 +1,24 @@
/*
* 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.beans;
public interface IOther {
void absquatulate();
}

View File

@@ -0,0 +1,71 @@
/*
* 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.beans;
import java.io.IOException;
/**
* Interface used for {@link org.springframework.beans.TestBean}.
*
* <p>Two methods are the same as on Person, but if this
* extends person it breaks quite a few tests..
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
String getName();
void setName(String name);
ITestBean getSpouse();
void setSpouse(ITestBean spouse);
ITestBean[] getSpouses();
String[] getStringArray();
void setStringArray(String[] stringArray);
/**
* Throws a given (non-null) exception.
*/
void exceptional(Throwable t) throws Throwable;
Object returnsThis();
INestedTestBean getDoctor();
INestedTestBean getLawyer();
IndexedTestBean getNestedIndexedBean();
/**
* Increment the age by one.
* @return the previous age
*/
int haveBirthday();
void unreliableFileOperation() throws IOException;
}

View File

@@ -0,0 +1,146 @@
/*
* Copyright 2002-2006 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.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Juergen Hoeller
* @since 11.11.2003
*/
@SuppressWarnings("rawtypes")
public class IndexedTestBean {
private TestBean[] array;
private Collection collection;
private List list;
private Set set;
private SortedSet sortedSet;
private Map map;
private SortedMap sortedMap;
public IndexedTestBean() {
this(true);
}
public IndexedTestBean(boolean populate) {
if (populate) {
populate();
}
}
@SuppressWarnings("unchecked")
public void populate() {
TestBean tb0 = new TestBean("name0", 0);
TestBean tb1 = new TestBean("name1", 0);
TestBean tb2 = new TestBean("name2", 0);
TestBean tb3 = new TestBean("name3", 0);
TestBean tb4 = new TestBean("name4", 0);
TestBean tb5 = new TestBean("name5", 0);
TestBean tb6 = new TestBean("name6", 0);
TestBean tb7 = new TestBean("name7", 0);
TestBean tbX = new TestBean("nameX", 0);
TestBean tbY = new TestBean("nameY", 0);
this.array = new TestBean[] { tb0, tb1 };
this.list = new ArrayList();
this.list.add(tb2);
this.list.add(tb3);
this.set = new TreeSet();
this.set.add(tb6);
this.set.add(tb7);
this.map = new HashMap();
this.map.put("key1", tb4);
this.map.put("key2", tb5);
this.map.put("key.3", tb5);
List list = new ArrayList();
list.add(tbX);
list.add(tbY);
this.map.put("key4", list);
}
public TestBean[] getArray() {
return array;
}
public void setArray(TestBean[] array) {
this.array = array;
}
public Collection getCollection() {
return collection;
}
public void setCollection(Collection collection) {
this.collection = collection;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Set getSet() {
return set;
}
public void setSet(Set set) {
this.set = set;
}
public SortedSet getSortedSet() {
return sortedSet;
}
public void setSortedSet(SortedSet sortedSet) {
this.sortedSet = sortedSet;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public SortedMap getSortedMap() {
return sortedMap;
}
public void setSortedMap(SortedMap sortedMap) {
this.sortedMap = sortedMap;
}
}

View File

@@ -0,0 +1,60 @@
/*
* 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.beans;
/**
* Simple nested test bean used for testing bean factories, AOP framework etc.
*
* @author Trevor D. Cook
* @since 30.09.2003
*/
public class NestedTestBean implements INestedTestBean {
private String company = "";
public NestedTestBean() {
}
public NestedTestBean(String company) {
setCompany(company);
}
public void setCompany(String company) {
this.company = (company != null ? company : "");
}
public String getCompany() {
return company;
}
public boolean equals(Object obj) {
if (!(obj instanceof NestedTestBean)) {
return false;
}
NestedTestBean ntb = (NestedTestBean) obj;
return this.company.equals(ntb.company);
}
public int hashCode() {
return this.company.hashCode();
}
public String toString() {
return "NestedTestBean: " + this.company;
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2006 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.beans;
/**
* @author Rob Harrop
* @since 2.0
*/
public class Pet {
private String name;
public Pet(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return getName();
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Pet pet = (Pet) o;
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
return true;
}
public int hashCode() {
return (name != null ? name.hashCode() : 0);
}
}

View File

@@ -0,0 +1,435 @@
/*
* Copyright 2002-2008 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.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.util.ObjectUtils;
/**
* Simple test bean used for testing bean factories, the AOP framework etc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 15 April 2001
*/
@SuppressWarnings("rawtypes")
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
private String beanName;
private String country;
private BeanFactory beanFactory;
private boolean postProcessed;
private String name;
private String sex;
private int age;
private boolean jedi;
private ITestBean[] spouses;
private String touchy;
private String[] stringArray;
private Integer[] someIntegerArray;
private Date date = new Date();
private Float myFloat = new Float(0.0);
private Collection friends = new LinkedList();
private Set someSet = new HashSet();
private Map someMap = new HashMap();
private List someList = new ArrayList();
private Properties someProperties = new Properties();
private INestedTestBean doctor = new NestedTestBean();
private INestedTestBean lawyer = new NestedTestBean();
private IndexedTestBean nestedIndexedBean;
private boolean destroyed;
private Number someNumber;
private Colour favouriteColour;
private Boolean someBoolean;
private List otherColours;
private List pets;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) {
this.spouses = new ITestBean[] { spouse };
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean(ITestBean spouse, Properties someProperties) {
this.spouses = new ITestBean[] { spouse };
this.someProperties = someProperties;
}
public TestBean(List someList) {
this.someList = someList;
}
public TestBean(Set someSet) {
this.someSet = someSet;
}
public TestBean(Map someMap) {
this.someMap = someMap;
}
public TestBean(Properties someProperties) {
this.someProperties = someProperties;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
if (this.name == null) {
this.name = sex;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
public ITestBean getSpouse() {
return (spouses != null ? spouses[0] : null);
}
public void setSpouse(ITestBean spouse) {
this.spouses = new ITestBean[] { spouse };
}
public ITestBean[] getSpouses() {
return spouses;
}
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
throw new Exception("Can't contain a .");
}
if (touchy.indexOf(',') != -1) {
throw new NumberFormatException("Number format exception: contains a ,");
}
this.touchy = touchy;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection getFriends() {
return friends;
}
public void setFriends(Collection friends) {
this.friends = friends;
}
public Set getSomeSet() {
return someSet;
}
public void setSomeSet(Set someSet) {
this.someSet = someSet;
}
public Map getSomeMap() {
return someMap;
}
public void setSomeMap(Map someMap) {
this.someMap = someMap;
}
public List getSomeList() {
return someList;
}
public void setSomeList(List someList) {
this.someList = someList;
}
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
public INestedTestBean getDoctor() {
return doctor;
}
public void setDoctor(INestedTestBean doctor) {
this.doctor = doctor;
}
public INestedTestBean getLawyer() {
return lawyer;
}
public void setLawyer(INestedTestBean lawyer) {
this.lawyer = lawyer;
}
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List getOtherColours() {
return otherColours;
}
public void setOtherColours(List otherColours) {
this.otherColours = otherColours;
}
public List getPets() {
return pets;
}
public void setPets(List pets) {
this.pets = pets;
}
/**
* @see ITestBean#exceptional(Throwable)
*/
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see ITestBean#returnsThis()
*/
public Object returnsThis() {
return this;
}
/**
* @see IOther#absquatulate()
*/
public void absquatulate() {
}
public int haveBirthday() {
return age++;
}
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() {
return destroyed;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof TestBean)) {
return false;
}
TestBean tb2 = (TestBean) other;
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
}
public int hashCode() {
return this.age;
}
public int compareTo(Object other) {
if (this.name != null && other instanceof TestBean) {
return this.name.compareTo(((TestBean) other).getName());
}
else {
return 1;
}
}
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,144 @@
/*
* Copyright 2002-2011 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.mock.web;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
/**
* @author Rick Evans
* @author Mark Fisher
* @author Rossen Stoyanchev
*/
public class MockHttpServletRequestTests extends TestCase {
public void testSetContentType() {
String contentType = "test/plain";
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType(contentType);
assertEquals(contentType, request.getContentType());
assertEquals(contentType, request.getHeader("Content-Type"));
assertNull(request.getCharacterEncoding());
}
public void testSetContentTypeUTF8() {
String contentType = "test/plain;charset=UTF-8";
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType(contentType);
assertEquals(contentType, request.getContentType());
assertEquals(contentType, request.getHeader("Content-Type"));
assertEquals("UTF-8", request.getCharacterEncoding());
}
public void testContentTypeHeader() {
String contentType = "test/plain";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Content-Type", contentType);
assertEquals(contentType, request.getContentType());
assertEquals(contentType, request.getHeader("Content-Type"));
assertNull(request.getCharacterEncoding());
}
public void testContentTypeHeaderUTF8() {
String contentType = "test/plain;charset=UTF-8";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Content-Type", contentType);
assertEquals(contentType, request.getContentType());
assertEquals(contentType, request.getHeader("Content-Type"));
assertEquals("UTF-8", request.getCharacterEncoding());
}
public void testSetContentTypeThenCharacterEncoding() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContentType("test/plain");
request.setCharacterEncoding("UTF-8");
assertEquals("test/plain", request.getContentType());
assertEquals("test/plain;charset=UTF-8", request.getHeader("Content-Type"));
assertEquals("UTF-8", request.getCharacterEncoding());
}
public void testSetCharacterEncodingThenContentType() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCharacterEncoding("UTF-8");
request.setContentType("test/plain");
assertEquals("test/plain", request.getContentType());
assertEquals("test/plain;charset=UTF-8", request.getHeader("Content-Type"));
assertEquals("UTF-8", request.getCharacterEncoding());
}
public void testHttpHeaderNameCasingIsPreserved() throws Exception {
String headerName = "Header1";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(headerName, "value1");
Enumeration<String> requestHeaders = request.getHeaderNames();
assertNotNull(requestHeaders);
assertEquals("HTTP header casing not being preserved", headerName, requestHeaders.nextElement());
}
public void testSetMultipleParameters() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("key1", "value1");
request.setParameter("key2", "value2");
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("key1", "newValue1");
params.put("key3", new String[] { "value3A", "value3B" });
request.setParameters(params);
String[] values1 = request.getParameterValues("key1");
assertEquals(1, values1.length);
assertEquals("newValue1", request.getParameter("key1"));
assertEquals("value2", request.getParameter("key2"));
String[] values3 = request.getParameterValues("key3");
assertEquals(2, values3.length);
assertEquals("value3A", values3[0]);
assertEquals("value3B", values3[1]);
}
public void testAddMultipleParameters() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("key1", "value1");
request.setParameter("key2", "value2");
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("key1", "newValue1");
params.put("key3", new String[] { "value3A", "value3B" });
request.addParameters(params);
String[] values1 = request.getParameterValues("key1");
assertEquals(2, values1.length);
assertEquals("value1", values1[0]);
assertEquals("newValue1", values1[1]);
assertEquals("value2", request.getParameter("key2"));
String[] values3 = request.getParameterValues("key3");
assertEquals(2, values3.length);
assertEquals("value3A", values3[0]);
assertEquals("value3B", values3[1]);
}
public void testRemoveAllParameters() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("key1", "value1");
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("key2", "value2");
params.put("key3", new String[] { "value3A", "value3B" });
request.addParameters(params);
assertEquals(3, request.getParameterMap().size());
request.removeAllParameters();
assertEquals(0, request.getParameterMap().size());
}
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright 2002-2011 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.mock.web;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.web.util.WebUtils;
/**
* @author Juergen Hoeller
* @author Rick Evans
* @author Rossen Stoyanchev
* @since 19.02.2006
*/
public class MockHttpServletResponseTests extends TestCase {
public void testSetContentType() {
String contentType = "test/plain";
MockHttpServletResponse response = new MockHttpServletResponse();
response.setContentType(contentType);
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding());
}
public void testSetContentTypeUTF8() {
String contentType = "test/plain;charset=UTF-8";
MockHttpServletResponse response = new MockHttpServletResponse();
response.setContentType(contentType);
assertEquals("UTF-8", response.getCharacterEncoding());
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
}
public void testContentTypeHeader() {
String contentType = "test/plain";
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", contentType);
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding());
response = new MockHttpServletResponse();
response.setHeader("Content-Type", contentType);
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding());
}
public void testContentTypeHeaderUTF8() {
String contentType = "test/plain;charset=UTF-8";
MockHttpServletResponse response = new MockHttpServletResponse();
response.setHeader("Content-Type", contentType);
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
assertEquals("UTF-8", response.getCharacterEncoding());
response = new MockHttpServletResponse();
response.addHeader("Content-Type", contentType);
assertEquals(contentType, response.getContentType());
assertEquals(contentType, response.getHeader("Content-Type"));
assertEquals("UTF-8", response.getCharacterEncoding());
}
public void testSetContentTypeThenCharacterEncoding() {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setContentType("test/plain");
response.setCharacterEncoding("UTF-8");
assertEquals("test/plain", response.getContentType());
assertEquals("test/plain;charset=UTF-8", response.getHeader("Content-Type"));
assertEquals("UTF-8", response.getCharacterEncoding());
}
public void testSetCharacterEncodingThenContentType() {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("test/plain");
assertEquals("test/plain", response.getContentType());
assertEquals("test/plain;charset=UTF-8", response.getHeader("Content-Type"));
assertEquals("UTF-8", response.getCharacterEncoding());
}
public void testContentLength() {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setContentLength(66);
assertEquals(66, response.getContentLength());
assertEquals("66", response.getHeader("Content-Length"));
}
public void testContentLengthHeader() {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Length", "66");
assertEquals(66,response.getContentLength());
assertEquals("66", response.getHeader("Content-Length"));
}
public void testHttpHeaderNameCasingIsPreserved() throws Exception {
final String headerName = "Header1";
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader(headerName, "value1");
Set<String> responseHeaders = response.getHeaderNames();
assertNotNull(responseHeaders);
assertEquals(1, responseHeaders.size());
assertEquals("HTTP header casing not being preserved", headerName, responseHeaders.iterator().next());
}
public void testServletOutputStreamCommittedWhenBufferSizeExceeded() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(response.isCommitted());
response.getOutputStream().write('X');
assertFalse(response.isCommitted());
int size = response.getBufferSize();
response.getOutputStream().write(new byte[size]);
assertTrue(response.isCommitted());
assertEquals(size + 1, response.getContentAsByteArray().length);
}
public void testServletOutputStreamCommittedOnFlushBuffer() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(response.isCommitted());
response.getOutputStream().write('X');
assertFalse(response.isCommitted());
response.flushBuffer();
assertTrue(response.isCommitted());
assertEquals(1, response.getContentAsByteArray().length);
}
public void testServletWriterCommittedWhenBufferSizeExceeded() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(response.isCommitted());
response.getWriter().write("X");
assertFalse(response.isCommitted());
int size = response.getBufferSize();
char[] data = new char[size];
Arrays.fill(data, 'p');
response.getWriter().write(data);
assertTrue(response.isCommitted());
assertEquals(size + 1, response.getContentAsByteArray().length);
}
public void testServletOutputStreamCommittedOnOutputStreamFlush() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(response.isCommitted());
response.getOutputStream().write('X');
assertFalse(response.isCommitted());
response.getOutputStream().flush();
assertTrue(response.isCommitted());
assertEquals(1, response.getContentAsByteArray().length);
}
public void testServletWriterCommittedOnWriterFlush() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
assertFalse(response.isCommitted());
response.getWriter().write("X");
assertFalse(response.isCommitted());
response.getWriter().flush();
assertTrue(response.isCommitted());
assertEquals(1, response.getContentAsByteArray().length);
}
public void testServletWriterAutoFlushedForString() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
response.getWriter().write("X");
assertEquals("X", response.getContentAsString());
}
public void testServletWriterAutoFlushedForChar() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
response.getWriter().write('X');
assertEquals("X", response.getContentAsString());
}
public void testServletWriterAutoFlushedForCharArray() throws IOException {
MockHttpServletResponse response = new MockHttpServletResponse();
response.getWriter().write("XY".toCharArray());
assertEquals("XY", response.getContentAsString());
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2002-2006 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.mock.web;
import junit.framework.TestCase;
import javax.servlet.jsp.PageContext;
/**
* Unit tests for the <code>MockPageContext</code> class.
*
* @author Rick Evans
*/
public final class MockPageContextTests extends TestCase {
public void testSetAttributeWithNoScopeUsesPageScope() throws Exception {
String key = "foo";
String value = "bar";
MockPageContext ctx = new MockPageContext();
ctx.setAttribute(key, value);
assertEquals(value, ctx.getAttribute(key, PageContext.PAGE_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.REQUEST_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.SESSION_SCOPE));
}
public void testRemoveAttributeWithNoScopeSpecifiedRemovesValueFromAllScopes() throws Exception {
String key = "foo";
String value = "bar";
MockPageContext ctx = new MockPageContext();
ctx.setAttribute(key, value, PageContext.APPLICATION_SCOPE);
ctx.removeAttribute(key);
assertNull(ctx.getAttribute(key, PageContext.PAGE_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.REQUEST_SCOPE));
assertNull(ctx.getAttribute(key, PageContext.SESSION_SCOPE));
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2011 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.mock.web;
import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 19.02.2006
*/
public class MockServletContextTests {
@Ignore
// fails to work under ant after move from .testsuite -> .test
@Test
public void testListFiles() {
MockServletContext sc = new MockServletContext("org/springframework/mock");
Set<?> paths = sc.getResourcePaths("/web");
assertNotNull(paths);
assertTrue(paths.contains("/web/MockServletContextTests.class"));
}
@Ignore
// fails to work under ant after move from .testsuite -> .test
@Test
public void testListSubdirectories() {
MockServletContext sc = new MockServletContext("org/springframework/mock");
Set<?> paths = sc.getResourcePaths("/");
assertNotNull(paths);
assertTrue(paths.contains("/web/"));
}
@Test
public void testListNonDirectory() {
MockServletContext sc = new MockServletContext("org/springframework/mock");
Set<?> paths = sc.getResourcePaths("/web/MockServletContextTests.class");
assertNull(paths);
}
@Test
public void testListInvalidPath() {
MockServletContext sc = new MockServletContext("org/springframework/mock");
Set<?> paths = sc.getResourcePaths("/web/invalid");
assertNull(paths);
}
@Test
public void testGetContext() {
MockServletContext sc = new MockServletContext();
MockServletContext sc2 = new MockServletContext();
sc.setContextPath("/");
sc.registerContext("/second", sc2);
assertSame(sc, sc.getContext("/"));
assertSame(sc2, sc.getContext("/second"));
}
@Test
public void testGetMimeType() {
MockServletContext sc = new MockServletContext();
assertEquals("text/html", sc.getMimeType("test.html"));
assertEquals("image/gif", sc.getMimeType("test.gif"));
}
@Test
public void testMinorVersion() {
MockServletContext sc = new MockServletContext();
assertEquals(5, sc.getMinorVersion());
sc.setMinorVersion(4);
assertEquals(4, sc.getMinorVersion());
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2007-2011 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.test;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
/**
* Abstract JUnit 3.8 based unit test which verifies new functionality requested
* in <a href="http://opensource.atlassian.com/projects/spring/browse/SPR-3550"
* target="_blank">SPR-3350</a>.
*
* @author Sam Brannen
* @since 2.5
*/
@SuppressWarnings("deprecation")
public abstract class AbstractSpr3350SingleSpringContextTests extends AbstractDependencyInjectionSpringContextTests {
private Pet cat;
public AbstractSpr3350SingleSpringContextTests() {
super();
}
public AbstractSpr3350SingleSpringContextTests(String name) {
super(name);
}
public final void setCat(final Pet cat) {
this.cat = cat;
}
/**
* Forcing concrete subclasses to provide a config path appropriate to the
* configured
* {@link #createBeanDefinitionReader(org.springframework.context.support.GenericApplicationContext)
* BeanDefinitionReader}.
*
* @see org.springframework.test.AbstractSingleSpringContextTests#getConfigPath()
*/
protected abstract String getConfigPath();
/**
* <p>
* Test which addresses the following issue raised in SPR-3350:
* </p>
* <p>
* {@link AbstractSingleSpringContextTests} always uses an
* {@link XmlBeanDefinitionReader} internally when creating the
* {@link ApplicationContext} inside
* {@link #createApplicationContext(String[])}. It would be nice to have the
* bean definition reader creation in a separate method so that subclasses
* can choose that individually without having to copy-n-paste code from
* createApplicationContext() to do the context creation and refresh.
* Consider JavaConfig where an Annotation based reader can be plugged in.
* </p>
*/
public final void testApplicationContextNotAutoCreated() {
assertNotNull("The cat field should have been autowired.", this.cat);
assertEquals("Garfield", this.cat.getName());
}
}

View File

@@ -0,0 +1,2 @@
cat.(class)=org.springframework.beans.Pet
cat.$0=Garfield

View File

@@ -0,0 +1,58 @@
/*
* Copyright 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.test;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
/**
* Concrete implementation of {@link AbstractSpr3350SingleSpringContextTests}
* which configures a {@link PropertiesBeanDefinitionReader} instead of the
* default {@link XmlBeanDefinitionReader}.
*
* @author Sam Brannen
* @since 2.5
*/
public class PropertiesBasedSpr3350SingleSpringContextTests extends AbstractSpr3350SingleSpringContextTests {
public PropertiesBasedSpr3350SingleSpringContextTests() {
super();
}
public PropertiesBasedSpr3350SingleSpringContextTests(String name) {
super(name);
}
/**
* Creates a new {@link PropertiesBeanDefinitionReader}.
*
* @see org.springframework.test.AbstractSingleSpringContextTests#createBeanDefinitionReader(org.springframework.context.support.GenericApplicationContext)
*/
protected final BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
return new PropertiesBeanDefinitionReader(context);
}
/**
* Returns
* &quot;PropertiesBasedSpr3350SingleSpringContextTests-context.properties&quot;.
*/
protected final String getConfigPath() {
return "PropertiesBasedSpr3350SingleSpringContextTests-context.properties";
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright 2007-2011 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.test;
/**
* JUnit 3.8 based unit test which verifies new functionality requested in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-3264"
* target="_blank">SPR-3264</a>.
*
* @author Sam Brannen
* @since 2.5
* @see Spr3264SingleSpringContextTests
*/
@SuppressWarnings("deprecation")
public class Spr3264DependencyInjectionSpringContextTests extends AbstractDependencyInjectionSpringContextTests {
public Spr3264DependencyInjectionSpringContextTests() {
super();
}
public Spr3264DependencyInjectionSpringContextTests(String name) {
super(name);
}
/**
* <p>
* Test which addresses the following issue raised in SPR-3264:
* </p>
* <p>
* AbstractDependencyInjectionSpringContextTests will try to apply
* auto-injection; this can be disabled but it has to be done manually
* inside the onSetUp...
* </p>
*/
public void testInjectDependenciesThrowsIllegalStateException() {
// Re-assert issues covered by Spr3264SingleSpringContextTests as a
// safety net.
assertNull("The ApplicationContext should NOT be automatically created if no 'locations' are defined.",
this.applicationContext);
assertEquals("Verifying the ApplicationContext load count.", 0, super.getLoadCount());
// Assert changes to AbstractDependencyInjectionSpringContextTests:
new AssertThrows(IllegalStateException.class) {
public void test() throws Exception {
Spr3264DependencyInjectionSpringContextTests.super.injectDependencies();
}
}.runTest();
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2007-2011 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.test;
/**
* JUnit 3.8 based unit test which verifies new functionality requested in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-3264"
* target="_blank">SPR-3264</a>.
*
* @author Sam Brannen
* @since 2.5
* @see Spr3264DependencyInjectionSpringContextTests
*/
@SuppressWarnings("deprecation")
public class Spr3264SingleSpringContextTests extends AbstractSingleSpringContextTests {
public Spr3264SingleSpringContextTests() {
super();
}
public Spr3264SingleSpringContextTests(String name) {
super(name);
}
/**
* <p>
* Test which addresses the following issue raised in SPR-3264:
* </p>
* <p>
* AbstractSingleSpringContextTests always expects an application context to
* be created even if no files/locations are specified which can lead to NPE
* problems or force an appCtx to be instantiated even if not needed.
* </p>
*/
public void testApplicationContextNotAutoCreated() {
assertNull("The ApplicationContext should NOT be automatically created if no 'locations' are defined.",
super.applicationContext);
assertEquals("Verifying the ApplicationContext load count.", 0, super.getLoadCount());
}
}

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="cat" class="org.springframework.beans.Pet">
<constructor-arg value="Garfield" />
</bean>
</beans>

View File

@@ -0,0 +1,44 @@
/*
* Copyright 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.test;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
/**
* Concrete implementation of {@link AbstractSpr3350SingleSpringContextTests}
* which is based on the default {@link XmlBeanDefinitionReader}.
*
* @author Sam Brannen
* @since 2.5
*/
public class XmlBasedSpr3350SingleSpringContextTests extends AbstractSpr3350SingleSpringContextTests {
public XmlBasedSpr3350SingleSpringContextTests() {
super();
}
public XmlBasedSpr3350SingleSpringContextTests(String name) {
super(name);
}
/**
* Returns &quot;XmlBasedSpr3350SingleSpringContextTests-context.xml&quot;.
*/
protected final String getConfigPath() {
return "XmlBasedSpr3350SingleSpringContextTests-context.xml";
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
</beans>

View File

@@ -0,0 +1,148 @@
/*
* Copyright 2002-2008 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.test.annotation;
import junit.framework.TestCase;
import junit.framework.TestResult;
/**
* Verifies proper handling of {@link IfProfileValue @IfProfileValue} and
* {@link ProfileValueSourceConfiguration @ProfileValueSourceConfiguration} in
* conjunction with {@link AbstractAnnotationAwareTransactionalTests}.
*
* @author Sam Brannen
* @since 2.5
*/
public class ProfileValueAnnotationAwareTransactionalTests extends TestCase {
private static final String NAME = "ProfileValueAnnotationAwareTransactionalTests.profile_value.name";
private static final String VALUE = "enigma";
public ProfileValueAnnotationAwareTransactionalTests() {
System.setProperty(NAME, VALUE);
}
private void runTestAndAssertCounters(Class<? extends DefaultProfileValueSourceTestCase> testCaseType,
String testName, int expectedInvocationCount, int expectedErrorCount, int expectedFailureCount)
throws Exception {
DefaultProfileValueSourceTestCase testCase = testCaseType.newInstance();
testCase.setName(testName);
TestResult testResult = testCase.run();
assertEquals("Verifying number of invocations for test method [" + testName + "].", expectedInvocationCount,
testCase.invocationCount);
assertEquals("Verifying number of errors for test method [" + testName + "].", expectedErrorCount,
testResult.errorCount());
assertEquals("Verifying number of failures for test method [" + testName + "].", expectedFailureCount,
testResult.failureCount());
}
private void runTests(Class<? extends DefaultProfileValueSourceTestCase> testCaseType) throws Exception {
runTestAndAssertCounters(testCaseType, "testIfProfileValueEmpty", 0, 0, 0);
runTestAndAssertCounters(testCaseType, "testIfProfileValueDisabledViaWrongName", 0, 0, 0);
runTestAndAssertCounters(testCaseType, "testIfProfileValueDisabledViaWrongValue", 0, 0, 0);
runTestAndAssertCounters(testCaseType, "testIfProfileValueEnabledViaSingleValue", 1, 0, 0);
runTestAndAssertCounters(testCaseType, "testIfProfileValueEnabledViaMultipleValues", 1, 0, 0);
runTestAndAssertCounters(testCaseType, "testIfProfileValueNotConfigured", 1, 0, 0);
}
public void testDefaultProfileValueSource() throws Exception {
assertEquals("Verifying the type of the configured ProfileValueSource.", SystemProfileValueSource.class,
new DefaultProfileValueSourceTestCase().getProfileValueSource().getClass());
runTests(DefaultProfileValueSourceTestCase.class);
}
public void testHardCodedProfileValueSource() throws Exception {
assertEquals("Verifying the type of the configured ProfileValueSource.", HardCodedProfileValueSource.class,
new HardCodedProfileValueSourceTestCase().getProfileValueSource().getClass());
runTests(HardCodedProfileValueSourceTestCase.class);
}
@SuppressWarnings("deprecation")
@org.junit.Ignore // causes https://gist.github.com/1165828
protected static class DefaultProfileValueSourceTestCase extends AbstractAnnotationAwareTransactionalTests {
int invocationCount = 0;
public DefaultProfileValueSourceTestCase() {
}
public ProfileValueSource getProfileValueSource() {
return super.profileValueSource;
}
@Override
protected String getConfigPath() {
return "ProfileValueAnnotationAwareTransactionalTests-context.xml";
}
@NotTransactional
@IfProfileValue(name = NAME)
public void testIfProfileValueEmpty() {
this.invocationCount++;
fail("The body of a disabled test should never be executed!");
}
@NotTransactional
@IfProfileValue(name = NAME + "X", value = VALUE)
public void testIfProfileValueDisabledViaWrongName() {
this.invocationCount++;
fail("The body of a disabled test should never be executed!");
}
@NotTransactional
@IfProfileValue(name = NAME, value = VALUE + "X")
public void testIfProfileValueDisabledViaWrongValue() {
this.invocationCount++;
fail("The body of a disabled test should never be executed!");
}
@NotTransactional
@IfProfileValue(name = NAME, value = VALUE)
public void testIfProfileValueEnabledViaSingleValue() {
this.invocationCount++;
}
@NotTransactional
@IfProfileValue(name = NAME, values = { "foo", VALUE, "bar" })
public void testIfProfileValueEnabledViaMultipleValues() {
this.invocationCount++;
}
@NotTransactional
public void testIfProfileValueNotConfigured() {
this.invocationCount++;
}
}
@ProfileValueSourceConfiguration(HardCodedProfileValueSource.class)
@org.junit.Ignore // causes https://gist.github.com/1165832
protected static class HardCodedProfileValueSourceTestCase extends DefaultProfileValueSourceTestCase {
}
public static class HardCodedProfileValueSource implements ProfileValueSource {
public String get(String key) {
return (key.equals(NAME) ? VALUE : null);
}
}
}

View File

@@ -0,0 +1,214 @@
/*
* Copyright 2002-2009 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.test.annotation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Unit tests for {@link ProfileValueUtils}.
*
* @author Sam Brannen
* @since 3.0
*/
public class ProfileValueUtilsTests {
private static final String NON_ANNOTATED_METHOD = "nonAnnotatedMethod";
private static final String ENABLED_ANNOTATED_METHOD = "enabledAnnotatedMethod";
private static final String DISABLED_ANNOTATED_METHOD = "disabledAnnotatedMethod";
private static final String NAME = "ProfileValueUtilsTests.profile_value.name";
private static final String VALUE = "enigma";
@BeforeClass
public static void setProfileValue() {
System.setProperty(NAME, VALUE);
}
private void assertClassIsEnabled(Class<?> testClass) throws Exception {
assertTrue("Test class [" + testClass + "] should be enabled.",
ProfileValueUtils.isTestEnabledInThisEnvironment(testClass));
}
private void assertClassIsDisabled(Class<?> testClass) throws Exception {
assertFalse("Test class [" + testClass + "] should be disbled.",
ProfileValueUtils.isTestEnabledInThisEnvironment(testClass));
}
private void assertMethodIsEnabled(String methodName, Class<?> testClass) throws Exception {
Method testMethod = testClass.getMethod(methodName);
assertTrue("Test method [" + testMethod + "] should be enabled.",
ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass));
}
private void assertMethodIsDisabled(String methodName, Class<?> testClass) throws Exception {
Method testMethod = testClass.getMethod(methodName);
assertFalse("Test method [" + testMethod + "] should be disabled.",
ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass));
}
private void assertMethodIsEnabled(ProfileValueSource profileValueSource, String methodName, Class<?> testClass)
throws Exception {
Method testMethod = testClass.getMethod(methodName);
assertTrue("Test method [" + testMethod + "] should be enabled for ProfileValueSource [" + profileValueSource
+ "].", ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass));
}
private void assertMethodIsDisabled(ProfileValueSource profileValueSource, String methodName, Class<?> testClass)
throws Exception {
Method testMethod = testClass.getMethod(methodName);
assertFalse("Test method [" + testMethod + "] should be disabled for ProfileValueSource [" + profileValueSource
+ "].", ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass));
}
// -------------------------------------------------------------------
@Test
public void isTestEnabledInThisEnvironmentForProvidedClass() throws Exception {
assertClassIsEnabled(NonAnnotated.class);
assertClassIsEnabled(EnabledAnnotatedSingleValue.class);
assertClassIsEnabled(EnabledAnnotatedMultiValue.class);
assertClassIsDisabled(DisabledAnnotatedSingleValue.class);
assertClassIsDisabled(DisabledAnnotatedMultiValue.class);
}
@Test
public void isTestEnabledInThisEnvironmentForProvidedMethodAndClass() throws Exception {
assertMethodIsEnabled(NON_ANNOTATED_METHOD, NonAnnotated.class);
assertMethodIsEnabled(NON_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsEnabled(ENABLED_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsDisabled(DISABLED_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsEnabled(NON_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsEnabled(ENABLED_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsDisabled(DISABLED_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsDisabled(NON_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(ENABLED_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(DISABLED_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(NON_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
assertMethodIsDisabled(ENABLED_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
assertMethodIsDisabled(DISABLED_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
}
@Test
public void isTestEnabledInThisEnvironmentForProvidedProfileValueSourceMethodAndClass() throws Exception {
ProfileValueSource profileValueSource = SystemProfileValueSource.getInstance();
assertMethodIsEnabled(profileValueSource, NON_ANNOTATED_METHOD, NonAnnotated.class);
assertMethodIsEnabled(profileValueSource, NON_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsEnabled(profileValueSource, ENABLED_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsDisabled(profileValueSource, DISABLED_ANNOTATED_METHOD, EnabledAnnotatedSingleValue.class);
assertMethodIsEnabled(profileValueSource, NON_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsEnabled(profileValueSource, ENABLED_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsDisabled(profileValueSource, DISABLED_ANNOTATED_METHOD, EnabledAnnotatedMultiValue.class);
assertMethodIsDisabled(profileValueSource, NON_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(profileValueSource, ENABLED_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(profileValueSource, DISABLED_ANNOTATED_METHOD, DisabledAnnotatedSingleValue.class);
assertMethodIsDisabled(profileValueSource, NON_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
assertMethodIsDisabled(profileValueSource, ENABLED_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
assertMethodIsDisabled(profileValueSource, DISABLED_ANNOTATED_METHOD, DisabledAnnotatedMultiValue.class);
}
// -------------------------------------------------------------------
@SuppressWarnings("unused")
private static class NonAnnotated {
public void nonAnnotatedMethod() {
}
}
@SuppressWarnings("unused")
@IfProfileValue(name = NAME, value = VALUE)
private static class EnabledAnnotatedSingleValue {
public void nonAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE)
public void enabledAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public void disabledAnnotatedMethod() {
}
}
@SuppressWarnings("unused")
@IfProfileValue(name = NAME, values = { "foo", VALUE, "bar" })
private static class EnabledAnnotatedMultiValue {
public void nonAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE)
public void enabledAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public void disabledAnnotatedMethod() {
}
}
@SuppressWarnings("unused")
@IfProfileValue(name = NAME, value = VALUE + "X")
private static class DisabledAnnotatedSingleValue {
public void nonAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE)
public void enabledAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public void disabledAnnotatedMethod() {
}
}
@SuppressWarnings("unused")
@IfProfileValue(name = NAME, values = { "foo", "bar" })
private static class DisabledAnnotatedMultiValue {
public void nonAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE)
public void enabledAnnotatedMethod() {
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public void disabledAnnotatedMethod() {
}
}
}

View File

@@ -0,0 +1,266 @@
/*
* Copyright 2002-2009 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.test.context;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.TrackingRunListener;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
/**
* JUnit 4 based integration test which verifies correct {@link ContextCache
* application context caching} in conjunction with the
* {@link SpringJUnit4ClassRunner} and the {@link DirtiesContext
* &#064;DirtiesContext} annotation at the class level.
*
* @author Sam Brannen
* @since 3.0
*/
@RunWith(JUnit4.class)
public class ClassLevelDirtiesContextTests {
private static final AtomicInteger cacheHits = new AtomicInteger(0);
private static final AtomicInteger cacheMisses = new AtomicInteger(0);
/**
* Asserts the statistics of the supplied context cache.
*
* @param usageScenario the scenario in which the statistics are used
* @param expectedSize the expected number of contexts in the cache
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
private static final void assertCacheStats(String usageScenario, int expectedSize, int expectedHitCount,
int expectedMissCount) {
ContextCache contextCache = TestContextManager.contextCache;
assertEquals("Verifying number of contexts in cache (" + usageScenario + ").", expectedSize,
contextCache.size());
assertEquals("Verifying number of cache hits (" + usageScenario + ").", expectedHitCount,
contextCache.getHitCount());
assertEquals("Verifying number of cache misses (" + usageScenario + ").", expectedMissCount,
contextCache.getMissCount());
}
private static final void runTestClassAndAssertStats(Class<?> testClass, int expectedTestCount) {
final int expectedTestFailureCount = 0;
final int expectedTestStartedCount = expectedTestCount;
final int expectedTestFinishedCount = expectedTestCount;
TrackingRunListener listener = new TrackingRunListener();
JUnitCore jUnitCore = new JUnitCore();
jUnitCore.addListener(listener);
jUnitCore.run(testClass);
assertEquals("Verifying number of failures for test class [" + testClass + "].", expectedTestFailureCount,
listener.getTestFailureCount());
assertEquals("Verifying number of tests started for test class [" + testClass + "].", expectedTestStartedCount,
listener.getTestStartedCount());
assertEquals("Verifying number of tests finished for test class [" + testClass + "].",
expectedTestFinishedCount, listener.getTestFinishedCount());
}
@BeforeClass
public static void verifyInitialCacheState() {
ContextCache contextCache = TestContextManager.contextCache;
contextCache.clear();
contextCache.clearStatistics();
cacheHits.set(0);
cacheMisses.set(0);
assertCacheStats("BeforeClass", 0, cacheHits.get(), cacheMisses.get());
}
@Test
public void verifyDirtiesContextBehavior() throws Exception {
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(ClassLevelDirtiesContextWithCleanMethodsAndDefaultModeTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with clean test method and default class mode", 0,
cacheHits.incrementAndGet(), cacheMisses.get());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithCleanMethodsAndDefaultModeTestCase.class, 1);
assertCacheStats("after inherited class-level @DirtiesContext with clean test method and default class mode",
0, cacheHits.incrementAndGet(), cacheMisses.get());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(ClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with clean test method and AFTER_CLASS mode", 0,
cacheHits.incrementAndGet(), cacheMisses.get());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase.class, 1);
assertCacheStats("after inherited class-level @DirtiesContext with clean test method and AFTER_CLASS mode", 0,
cacheHits.incrementAndGet(), cacheMisses.get());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(ClassLevelDirtiesContextWithAfterEachTestMethodModeTestCase.class, 3);
assertCacheStats("after class-level @DirtiesContext with clean test method and AFTER_EACH_TEST_METHOD mode", 0,
cacheHits.incrementAndGet(), cacheMisses.addAndGet(2));
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithAfterEachTestMethodModeTestCase.class, 3);
assertCacheStats(
"after inherited class-level @DirtiesContext with clean test method and AFTER_EACH_TEST_METHOD mode", 0,
cacheHits.incrementAndGet(), cacheMisses.addAndGet(2));
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(ClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with dirty test method", 0, cacheHits.incrementAndGet(),
cacheMisses.get());
runTestClassAndAssertStats(ClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with dirty test method", 0, cacheHits.get(),
cacheMisses.incrementAndGet());
runTestClassAndAssertStats(ClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with dirty test method", 0, cacheHits.get(),
cacheMisses.incrementAndGet());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after inherited class-level @DirtiesContext with dirty test method", 0,
cacheHits.incrementAndGet(), cacheMisses.get());
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after inherited class-level @DirtiesContext with dirty test method", 0, cacheHits.get(),
cacheMisses.incrementAndGet());
runTestClassAndAssertStats(InheritedClassLevelDirtiesContextWithDirtyMethodsTestCase.class, 1);
assertCacheStats("after inherited class-level @DirtiesContext with dirty test method", 0, cacheHits.get(),
cacheMisses.incrementAndGet());
assertBehaviorForCleanTestCase();
runTestClassAndAssertStats(ClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase.class, 1);
assertCacheStats("after class-level @DirtiesContext with clean test method and AFTER_CLASS mode", 0,
cacheHits.incrementAndGet(), cacheMisses.get());
}
private void assertBehaviorForCleanTestCase() {
runTestClassAndAssertStats(CleanTestCase.class, 1);
assertCacheStats("after clean test class", 1, cacheHits.get(), cacheMisses.incrementAndGet());
}
@AfterClass
public static void verifyFinalCacheState() {
assertCacheStats("AfterClass", 0, cacheHits.get(), cacheMisses.get());
}
// -------------------------------------------------------------------
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
@ContextConfiguration("/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml")
public static abstract class BaseTestCase {
@Autowired
protected ApplicationContext applicationContext;
protected void assertApplicationContextWasAutowired() {
assertNotNull("The application context should have been autowired.", this.applicationContext);
}
}
public static final class CleanTestCase extends BaseTestCase {
@Test
public void verifyContextWasAutowired() {
assertApplicationContextWasAutowired();
}
}
@DirtiesContext
public static class ClassLevelDirtiesContextWithCleanMethodsAndDefaultModeTestCase extends BaseTestCase {
@Test
public void verifyContextWasAutowired() {
assertApplicationContextWasAutowired();
}
}
public static class InheritedClassLevelDirtiesContextWithCleanMethodsAndDefaultModeTestCase extends
ClassLevelDirtiesContextWithCleanMethodsAndDefaultModeTestCase {
}
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public static class ClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase extends BaseTestCase {
@Test
public void verifyContextWasAutowired() {
assertApplicationContextWasAutowired();
}
}
public static class InheritedClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase extends
ClassLevelDirtiesContextWithCleanMethodsAndAfterClassModeTestCase {
}
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public static class ClassLevelDirtiesContextWithAfterEachTestMethodModeTestCase extends BaseTestCase {
@Test
public void verifyContextWasAutowired1() {
assertApplicationContextWasAutowired();
}
@Test
public void verifyContextWasAutowired2() {
assertApplicationContextWasAutowired();
}
@Test
public void verifyContextWasAutowired3() {
assertApplicationContextWasAutowired();
}
}
public static class InheritedClassLevelDirtiesContextWithAfterEachTestMethodModeTestCase extends
ClassLevelDirtiesContextWithAfterEachTestMethodModeTestCase {
}
@DirtiesContext
public static class ClassLevelDirtiesContextWithDirtyMethodsTestCase extends BaseTestCase {
@Test
@DirtiesContext
public void dirtyContext() {
assertApplicationContextWasAutowired();
}
}
public static class InheritedClassLevelDirtiesContextWithDirtyMethodsTestCase extends
ClassLevelDirtiesContextWithDirtyMethodsTestCase {
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- intentionally empty: only needed so that the ContextLoader can find this file -->
</beans>

View File

@@ -0,0 +1,345 @@
/*
* Copyright 2002-2011 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.test.context;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
import org.springframework.test.context.support.GenericPropertiesContextLoader;
/**
* Unit tests for {@link ContextLoaderUtils}.
*
* @author Sam Brannen
* @since 3.1
*/
public class ContextLoaderUtilsTests {
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private void assertAttributes(ContextConfigurationAttributes attributes, Class<?> expectedDeclaringClass,
String[] expectedLocations, Class<?>[] expectedClasses,
Class<? extends ContextLoader> expectedContextLoaderClass, boolean expectedInheritLocations) {
assertEquals(expectedDeclaringClass, attributes.getDeclaringClass());
assertArrayEquals(expectedLocations, attributes.getLocations());
assertArrayEquals(expectedClasses, attributes.getClasses());
assertEquals(expectedInheritLocations, attributes.isInheritLocations());
assertEquals(expectedContextLoaderClass, attributes.getContextLoaderClass());
}
private void assertLocationsFooAttributes(ContextConfigurationAttributes attributes) {
assertAttributes(attributes, LocationsFoo.class, new String[] { "/foo.xml" }, EMPTY_CLASS_ARRAY,
ContextLoader.class, false);
}
private void assertClassesFooAttributes(ContextConfigurationAttributes attributes) {
assertAttributes(attributes, ClassesFoo.class, EMPTY_STRING_ARRAY, new Class<?>[] { FooConfig.class },
ContextLoader.class, false);
}
private void assertLocationsBarAttributes(ContextConfigurationAttributes attributes) {
assertAttributes(attributes, LocationsBar.class, new String[] { "/bar.xml" }, EMPTY_CLASS_ARRAY,
AnnotationConfigContextLoader.class, true);
}
private void assertClassesBarAttributes(ContextConfigurationAttributes attributes) {
assertAttributes(attributes, ClassesBar.class, EMPTY_STRING_ARRAY, new Class<?>[] { BarConfig.class },
AnnotationConfigContextLoader.class, true);
}
private void assertMergedContextConfiguration(MergedContextConfiguration mergedConfig, Class<?> expectedTestClass,
String[] expectedLocations, Class<?>[] expectedClasses,
Class<? extends ContextLoader> expectedContextLoaderClass) {
assertNotNull(mergedConfig);
assertEquals(expectedTestClass, mergedConfig.getTestClass());
assertNotNull(mergedConfig.getLocations());
assertArrayEquals(expectedLocations, mergedConfig.getLocations());
assertNotNull(mergedConfig.getClasses());
assertArrayEquals(expectedClasses, mergedConfig.getClasses());
assertNotNull(mergedConfig.getActiveProfiles());
assertEquals(expectedContextLoaderClass, mergedConfig.getContextLoader().getClass());
}
@Test(expected = IllegalStateException.class)
public void resolveContextConfigurationAttributesWithConflictingLocations() {
ContextLoaderUtils.resolveContextConfigurationAttributes(ConflictingLocations.class);
}
@Test
public void resolveContextConfigurationAttributesWithBareAnnotations() {
List<ContextConfigurationAttributes> attributesList = ContextLoaderUtils.resolveContextConfigurationAttributes(BareAnnotations.class);
assertNotNull(attributesList);
assertEquals(1, attributesList.size());
assertAttributes(attributesList.get(0), BareAnnotations.class, EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY,
ContextLoader.class, true);
}
@Test
public void resolveContextConfigurationAttributesWithLocalAnnotationAndLocations() {
List<ContextConfigurationAttributes> attributesList = ContextLoaderUtils.resolveContextConfigurationAttributes(LocationsFoo.class);
assertNotNull(attributesList);
assertEquals(1, attributesList.size());
assertLocationsFooAttributes(attributesList.get(0));
}
@Test
public void resolveContextConfigurationAttributesWithLocalAnnotationAndClasses() {
List<ContextConfigurationAttributes> attributesList = ContextLoaderUtils.resolveContextConfigurationAttributes(ClassesFoo.class);
assertNotNull(attributesList);
assertEquals(1, attributesList.size());
assertClassesFooAttributes(attributesList.get(0));
}
@Test
public void resolveContextConfigurationAttributesWithLocalAndInheritedAnnotationsAndLocations() {
List<ContextConfigurationAttributes> attributesList = ContextLoaderUtils.resolveContextConfigurationAttributes(LocationsBar.class);
assertNotNull(attributesList);
assertEquals(2, attributesList.size());
assertLocationsFooAttributes(attributesList.get(0));
assertLocationsBarAttributes(attributesList.get(1));
}
@Test
public void resolveContextConfigurationAttributesWithLocalAndInheritedAnnotationsAndClasses() {
List<ContextConfigurationAttributes> attributesList = ContextLoaderUtils.resolveContextConfigurationAttributes(ClassesBar.class);
assertNotNull(attributesList);
assertEquals(2, attributesList.size());
assertClassesFooAttributes(attributesList.get(0));
assertClassesBarAttributes(attributesList.get(1));
}
@Test(expected = IllegalArgumentException.class)
public void buildMergedContextConfigurationWithoutAnnotation() {
ContextLoaderUtils.buildMergedContextConfiguration(Enigma.class, null);
}
@Test
public void buildMergedContextConfigurationWithBareAnnotations() {
Class<BareAnnotations> testClass = BareAnnotations.class;
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass, null);
assertMergedContextConfiguration(
mergedConfig,
testClass,
new String[] { "classpath:/org/springframework/test/context/ContextLoaderUtilsTests$BareAnnotations-context.xml" },
EMPTY_CLASS_ARRAY, DelegatingSmartContextLoader.class);
}
@Test
public void buildMergedContextConfigurationWithLocalAnnotationAndLocations() {
Class<?> testClass = LocationsFoo.class;
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass, null);
assertMergedContextConfiguration(mergedConfig, testClass, new String[] { "classpath:/foo.xml" },
EMPTY_CLASS_ARRAY, DelegatingSmartContextLoader.class);
}
@Test
public void buildMergedContextConfigurationWithLocalAnnotationAndClasses() {
Class<?> testClass = ClassesFoo.class;
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass, null);
assertMergedContextConfiguration(mergedConfig, testClass, EMPTY_STRING_ARRAY,
new Class<?>[] { FooConfig.class }, DelegatingSmartContextLoader.class);
}
@Test
public void buildMergedContextConfigurationWithLocalAnnotationAndOverriddenContextLoaderAndLocations() {
Class<?> testClass = LocationsFoo.class;
Class<? extends ContextLoader> expectedContextLoaderClass = GenericPropertiesContextLoader.class;
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass,
expectedContextLoaderClass.getName());
assertMergedContextConfiguration(mergedConfig, testClass, new String[] { "classpath:/foo.xml" },
EMPTY_CLASS_ARRAY, expectedContextLoaderClass);
}
@Test
public void buildMergedContextConfigurationWithLocalAnnotationAndOverriddenContextLoaderAndClasses() {
Class<?> testClass = ClassesFoo.class;
Class<? extends ContextLoader> expectedContextLoaderClass = GenericPropertiesContextLoader.class;
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass,
expectedContextLoaderClass.getName());
assertMergedContextConfiguration(mergedConfig, testClass, EMPTY_STRING_ARRAY,
new Class<?>[] { FooConfig.class }, expectedContextLoaderClass);
}
@Test
public void buildMergedContextConfigurationWithLocalAndInheritedAnnotationsAndLocations() {
Class<?> testClass = LocationsBar.class;
String[] expectedLocations = new String[] { "/foo.xml", "/bar.xml" };
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass, null);
assertMergedContextConfiguration(mergedConfig, testClass, expectedLocations, EMPTY_CLASS_ARRAY,
AnnotationConfigContextLoader.class);
}
@Test
public void buildMergedContextConfigurationWithLocalAndInheritedAnnotationsAndClasses() {
Class<?> testClass = ClassesBar.class;
Class<?>[] expectedClasses = new Class<?>[] { FooConfig.class, BarConfig.class };
MergedContextConfiguration mergedConfig = ContextLoaderUtils.buildMergedContextConfiguration(testClass, null);
assertMergedContextConfiguration(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses,
AnnotationConfigContextLoader.class);
}
@Test
public void resolveActiveProfilesWithoutAnnotation() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(Enigma.class);
assertArrayEquals(EMPTY_STRING_ARRAY, profiles);
}
@Test
public void resolveActiveProfilesWithNoProfilesDeclared() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(BareAnnotations.class);
assertArrayEquals(EMPTY_STRING_ARRAY, profiles);
}
@Test
public void resolveActiveProfilesWithEmptyProfiles() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(EmptyProfiles.class);
assertArrayEquals(EMPTY_STRING_ARRAY, profiles);
}
@Test
public void resolveActiveProfilesWithDuplicatedProfiles() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(DuplicatedProfiles.class);
assertNotNull(profiles);
assertEquals(3, profiles.length);
List<String> list = Arrays.asList(profiles);
assertTrue(list.contains("foo"));
assertTrue(list.contains("bar"));
assertTrue(list.contains("baz"));
}
@Test
public void resolveActiveProfilesWithLocalAnnotation() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(LocationsFoo.class);
assertNotNull(profiles);
assertArrayEquals(new String[] { "foo" }, profiles);
}
@Test
public void resolveActiveProfilesWithInheritedAnnotationAndLocations() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(InheritedLocationsFoo.class);
assertNotNull(profiles);
assertArrayEquals(new String[] { "foo" }, profiles);
}
@Test
public void resolveActiveProfilesWithInheritedAnnotationAndClasses() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(InheritedClassesFoo.class);
assertNotNull(profiles);
assertArrayEquals(new String[] { "foo" }, profiles);
}
@Test
public void resolveActiveProfilesWithLocalAndInheritedAnnotations() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(LocationsBar.class);
assertNotNull(profiles);
assertEquals(2, profiles.length);
List<String> list = Arrays.asList(profiles);
assertTrue(list.contains("foo"));
assertTrue(list.contains("bar"));
}
@Test
public void resolveActiveProfilesWithOverriddenAnnotation() {
String[] profiles = ContextLoaderUtils.resolveActiveProfiles(Animals.class);
assertNotNull(profiles);
assertEquals(2, profiles.length);
List<String> list = Arrays.asList(profiles);
assertTrue(list.contains("dog"));
assertTrue(list.contains("cat"));
}
private static class Enigma {
}
@ContextConfiguration(value = "x", locations = "y")
private static class ConflictingLocations {
}
@ContextConfiguration
@ActiveProfiles
private static class BareAnnotations {
}
@ActiveProfiles({ " ", "\t" })
private static class EmptyProfiles {
}
@ActiveProfiles({ "foo", "bar", " foo", "bar ", "baz" })
private static class DuplicatedProfiles {
}
@Configuration
private static class FooConfig {
}
@ContextConfiguration(locations = "/foo.xml", inheritLocations = false)
@ActiveProfiles(profiles = "foo")
private static class LocationsFoo {
}
@ContextConfiguration(classes = FooConfig.class, inheritLocations = false)
@ActiveProfiles(profiles = "foo")
private static class ClassesFoo {
}
private static class InheritedLocationsFoo extends LocationsFoo {
}
private static class InheritedClassesFoo extends ClassesFoo {
}
@Configuration
private static class BarConfig {
}
@ContextConfiguration(locations = "/bar.xml", inheritLocations = true, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("bar")
private static class LocationsBar extends LocationsFoo {
}
@ContextConfiguration(classes = BarConfig.class, inheritLocations = true, loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("bar")
private static class ClassesBar extends ClassesFoo {
}
@ActiveProfiles(profiles = { "dog", "cat" }, inheritProfiles = false)
private static class Animals extends LocationsBar {
}
}

View File

@@ -0,0 +1,283 @@
/*
* Copyright 2002-2011 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.test.context;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.GenericXmlContextLoader;
/**
* Unit tests for {@link MergedContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
*/
public class MergedContextConfigurationTests {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private final GenericXmlContextLoader loader = new GenericXmlContextLoader();
@Test
public void hashCodeWithNulls() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(null, null, null, null, null);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(null, null, null, null, null);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithNullArrays() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), null, null, null, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), null, null, null, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithEmptyArrays() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithEmptyArraysAndDifferentLoaders() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader());
assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode());
}
@Test
public void hashCodeWithSameLocations() {
String[] locations = new String[] { "foo", "bar}" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), locations,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithDifferentLocations() {
String[] locations1 = new String[] { "foo", "bar}" };
String[] locations2 = new String[] { "baz", "quux}" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), locations1,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode());
}
@Test
public void hashCodeWithSameConfigClasses() {
Class<?>[] classes = new Class<?>[] { String.class, Integer.class };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithDifferentConfigClasses() {
Class<?>[] classes1 = new Class<?>[] { String.class, Integer.class };
Class<?>[] classes2 = new Class<?>[] { Boolean.class, Number.class };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes1, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes2, EMPTY_STRING_ARRAY, loader);
assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode());
}
@Test
public void hashCodeWithSameProfiles() {
String[] activeProfiles = new String[] { "catbert", "dogbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithSameProfilesReversed() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "dogbert", "catbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithSameDuplicateProfiles() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "catbert", "dogbert", "catbert", "dogbert", "catbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
}
@Test
public void hashCodeWithDifferentProfiles() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "X", "Y" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode());
}
@Test
public void equalsBasics() {
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(null, null, null, null, null);
assertTrue(mergedConfig.equals(mergedConfig));
assertFalse(mergedConfig.equals(null));
assertFalse(mergedConfig.equals(new Integer(1)));
}
@Test
public void equalsWithNulls() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(null, null, null, null, null);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(null, null, null, null, null);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithNullArrays() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), null, null, null, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), null, null, null, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithEmptyArrays() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithEmptyArraysAndDifferentLoaders() {
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader());
assertFalse(mergedConfig1.equals(mergedConfig2));
}
@Test
public void equalsWithSameLocations() {
String[] locations = new String[] { "foo", "bar}" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), locations,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithDifferentLocations() {
String[] locations1 = new String[] { "foo", "bar}" };
String[] locations2 = new String[] { "baz", "quux}" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), locations1,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2,
EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
assertFalse(mergedConfig1.equals(mergedConfig2));
}
@Test
public void equalsWithSameConfigClasses() {
Class<?>[] classes = new Class<?>[] { String.class, Integer.class };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes, EMPTY_STRING_ARRAY, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithDifferentConfigClasses() {
Class<?>[] classes1 = new Class<?>[] { String.class, Integer.class };
Class<?>[] classes2 = new Class<?>[] { Boolean.class, Number.class };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes1, EMPTY_STRING_ARRAY, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
classes2, EMPTY_STRING_ARRAY, loader);
assertFalse(mergedConfig1.equals(mergedConfig2));
}
@Test
public void equalsWithSameProfiles() {
String[] activeProfiles = new String[] { "catbert", "dogbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithSameProfilesReversed() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "dogbert", "catbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithSameDuplicateProfiles() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "catbert", "dogbert", "catbert", "dogbert", "catbert" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertEquals(mergedConfig1, mergedConfig2);
}
@Test
public void equalsWithDifferentProfiles() {
String[] activeProfiles1 = new String[] { "catbert", "dogbert" };
String[] activeProfiles2 = new String[] { "X", "Y" };
MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles1, loader);
MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
EMPTY_CLASS_ARRAY, activeProfiles2, loader);
assertFalse(mergedConfig1.equals(mergedConfig2));
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright 2002-2011 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.test.context;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* JUnit 4 based unit test which verifies correct {@link ContextCache
* application context caching} in conjunction with the
* {@link SpringJUnit4ClassRunner} and the {@link DirtiesContext
* &#064;DirtiesContext} annotation at the method level.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 2.5
* @see TestContextCacheKeyTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml")
public class SpringRunnerContextCacheTests {
private static ApplicationContext dirtiedApplicationContext;
@Autowired
protected ApplicationContext applicationContext;
/**
* Asserts the statistics of the context cache in {@link TestContextManager}.
*
* @param usageScenario the scenario in which the statistics are used
* @param expectedSize the expected number of contexts in the cache
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
private static final void assertContextCacheStatistics(String usageScenario, int expectedSize,
int expectedHitCount, int expectedMissCount) {
assertContextCacheStatistics(TestContextManager.contextCache, usageScenario, expectedSize, expectedHitCount,
expectedMissCount);
}
/**
* Asserts the statistics of the supplied context cache.
*
* @param contextCache the cache to assert against
* @param usageScenario the scenario in which the statistics are used
* @param expectedSize the expected number of contexts in the cache
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
public static final void assertContextCacheStatistics(ContextCache contextCache, String usageScenario,
int expectedSize, int expectedHitCount, int expectedMissCount) {
assertEquals("Verifying number of contexts in cache (" + usageScenario + ").", expectedSize,
contextCache.size());
assertEquals("Verifying number of cache hits (" + usageScenario + ").", expectedHitCount,
contextCache.getHitCount());
assertEquals("Verifying number of cache misses (" + usageScenario + ").", expectedMissCount,
contextCache.getMissCount());
}
@BeforeClass
public static void verifyInitialCacheState() {
dirtiedApplicationContext = null;
ContextCache contextCache = TestContextManager.contextCache;
contextCache.clear();
contextCache.clearStatistics();
assertContextCacheStatistics("BeforeClass", 0, 0, 0);
}
@AfterClass
public static void verifyFinalCacheState() {
assertContextCacheStatistics("AfterClass", 1, 1, 2);
}
@Test
@DirtiesContext
public void dirtyContext() {
assertContextCacheStatistics("dirtyContext()", 1, 0, 1);
assertNotNull("The application context should have been autowired.", this.applicationContext);
SpringRunnerContextCacheTests.dirtiedApplicationContext = this.applicationContext;
}
@Test
public void verifyContextWasDirtied() {
assertContextCacheStatistics("verifyContextWasDirtied()", 1, 0, 2);
assertNotNull("The application context should have been autowired.", this.applicationContext);
assertNotSame("The application context should have been 'dirtied'.",
SpringRunnerContextCacheTests.dirtiedApplicationContext, this.applicationContext);
SpringRunnerContextCacheTests.dirtiedApplicationContext = this.applicationContext;
}
@Test
public void verifyContextWasNotDirtied() {
assertContextCacheStatistics("verifyContextWasNotDirtied()", 1, 1, 2);
assertNotNull("The application context should have been autowired.", this.applicationContext);
assertSame("The application context should NOT have been 'dirtied'.",
SpringRunnerContextCacheTests.dirtiedApplicationContext, this.applicationContext);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2002-2011 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.test.context;
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.context.SpringRunnerContextCacheTests.assertContextCacheStatistics;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* Unit tests for verifying proper behavior of the {@link ContextCache} in
* conjunction with cache keys used in {@link TestContext}.
*
* @author Sam Brannen
* @since 3.1
* @see SpringRunnerContextCacheTests
*/
public class TestContextCacheKeyTests {
private ContextCache contextCache = new ContextCache();
@Before
public void initialCacheState() {
assertContextCacheStatistics(contextCache, "initial state", 0, 0, 0);
}
private void loadAppCtxAndAssertCacheStats(Class<?> testClass, int expectedSize, int expectedHitCount,
int expectedMissCount) {
TestContext testContext = new TestContext(testClass, contextCache);
ApplicationContext context = testContext.getApplicationContext();
assertNotNull(context);
assertContextCacheStatistics(contextCache, testClass.getName(), expectedSize, expectedHitCount,
expectedMissCount);
}
@Test
public void verifyCacheKeyIsBasedOnContextLoader() {
loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 1, 0, 1);
loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 1, 1, 1);
loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 1, 2);
loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 2, 2);
loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 2, 3, 2);
loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 4, 2);
}
@Test
public void verifyCacheKeyIsBasedOnActiveProfiles() {
loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 0, 1);
loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 1, 1);
// Profiles {foo, bar} should hash to the same as {bar,foo}
loadAppCtxAndAssertCacheStats(BarFooProfilesTestCase.class, 1, 2, 1);
loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 3, 1);
loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 4, 1);
loadAppCtxAndAssertCacheStats(BarFooProfilesTestCase.class, 1, 5, 1);
}
@Configuration
static class Config {
}
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class AnnotationConfigContextLoaderTestCase {
}
@ContextConfiguration(classes = Config.class, loader = CustomAnnotationConfigContextLoader.class)
private static class CustomAnnotationConfigContextLoaderTestCase {
}
private static class CustomAnnotationConfigContextLoader extends AnnotationConfigContextLoader {
}
@ActiveProfiles({ "foo", "bar" })
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class FooBarProfilesTestCase {
}
@ActiveProfiles({ "bar", "foo" })
@ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class)
private static class BarFooProfilesTestCase {
}
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright 2002-2011 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.test.context;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.core.style.ToStringCreator;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* JUnit 4 based unit test for {@link TestContextManager}, which verifies proper
* <em>execution order</em> of registered {@link TestExecutionListener
* TestExecutionListeners}.
*
* @author Sam Brannen
* @since 2.5
*/
public class TestContextManagerTests {
private static final String FIRST = "veni";
private static final String SECOND = "vidi";
private static final String THIRD = "vici";
private static final List<String> afterTestMethodCalls = new ArrayList<String>();
private static final List<String> beforeTestMethodCalls = new ArrayList<String>();
protected static final Log logger = LogFactory.getLog(TestContextManagerTests.class);
private final TestContextManager testContextManager = new TestContextManager(ExampleTestCase.class);
private Method getTestMethod() throws NoSuchMethodException {
return ExampleTestCase.class.getDeclaredMethod("exampleTestMethod", (Class<?>[]) null);
}
/**
* Asserts the <em>execution order</em> of 'before' and 'after' test method
* calls on {@link TestExecutionListener listeners} registered for the
* configured {@link TestContextManager}.
*
* @see #beforeTestMethodCalls
* @see #afterTestMethodCalls
*/
private static void assertExecutionOrder(List<String> expectedBeforeTestMethodCalls,
List<String> expectedAfterTestMethodCalls, final String usageContext) {
if (expectedBeforeTestMethodCalls == null) {
expectedBeforeTestMethodCalls = new ArrayList<String>();
}
if (expectedAfterTestMethodCalls == null) {
expectedAfterTestMethodCalls = new ArrayList<String>();
}
if (logger.isDebugEnabled()) {
for (String listenerName : beforeTestMethodCalls) {
logger.debug("'before' listener [" + listenerName + "] (" + usageContext + ").");
}
for (String listenerName : afterTestMethodCalls) {
logger.debug("'after' listener [" + listenerName + "] (" + usageContext + ").");
}
}
assertTrue("Verifying execution order of 'before' listeners' (" + usageContext + ").",
expectedBeforeTestMethodCalls.equals(beforeTestMethodCalls));
assertTrue("Verifying execution order of 'after' listeners' (" + usageContext + ").",
expectedAfterTestMethodCalls.equals(afterTestMethodCalls));
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
beforeTestMethodCalls.clear();
afterTestMethodCalls.clear();
assertExecutionOrder(null, null, "BeforeClass");
}
/**
* Verifies the expected {@link TestExecutionListener}
* <em>execution order</em> after all test methods have completed.
*/
@AfterClass
public static void verifyListenerExecutionOrderAfterClass() throws Exception {
assertExecutionOrder(Arrays.<String> asList(FIRST, SECOND, THIRD),
Arrays.<String> asList(THIRD, SECOND, FIRST), "AfterClass");
}
@Before
public void setUpTestContextManager() throws Throwable {
assertEquals("Verifying the number of registered TestExecutionListeners.", 3,
this.testContextManager.getTestExecutionListeners().size());
this.testContextManager.beforeTestMethod(new ExampleTestCase(), getTestMethod());
}
/**
* Verifies the expected {@link TestExecutionListener}
* <em>execution order</em> within a test method.
*
* @see #verifyListenerExecutionOrderAfterClass()
*/
@Test
public void verifyListenerExecutionOrderWithinTestMethod() {
assertExecutionOrder(Arrays.<String> asList(FIRST, SECOND, THIRD), null, "Test");
}
@After
public void tearDownTestContextManager() throws Throwable {
this.testContextManager.afterTestMethod(new ExampleTestCase(), getTestMethod(), null);
}
@TestExecutionListeners({ FirstTel.class, SecondTel.class, ThirdTel.class })
private static class ExampleTestCase {
@SuppressWarnings("unused")
public void exampleTestMethod() {
assertTrue(true);
}
}
private static class NamedTestExecutionListener extends AbstractTestExecutionListener {
private final String name;
public NamedTestExecutionListener(final String name) {
this.name = name;
}
@Override
public void beforeTestMethod(final TestContext testContext) {
beforeTestMethodCalls.add(this.name);
}
@Override
public void afterTestMethod(final TestContext testContext) {
afterTestMethodCalls.add(this.name);
}
@Override
public String toString() {
return new ToStringCreator(this).append("name", this.name).toString();
}
}
private static class FirstTel extends NamedTestExecutionListener {
public FirstTel() {
super(FIRST);
}
}
private static class SecondTel extends NamedTestExecutionListener {
public SecondTel() {
super(SECOND);
}
}
private static class ThirdTel extends NamedTestExecutionListener {
public ThirdTel() {
super(THIRD);
}
}
}

View File

@@ -0,0 +1,153 @@
/*
* Copyright 2002-2009 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.test.context;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* <p>
* JUnit 4 based unit test for the {@link TestExecutionListeners
* &#064;TestExecutionListeners} annotation, which verifies:
* </p>
* <ul>
* <li>Proper registering of {@link TestExecutionListener listeners} in
* conjunction with a {@link TestContextManager}</li>
* <li><em>Inherited</em> functionality proposed in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-3896"
* target="_blank">SPR-3896</a></li>
* </ul>
*
* @author Sam Brannen
* @since 2.5
*/
public class TestExecutionListenersTests {
@Test
public void verifyNumDefaultListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(DefaultListenersExampleTestCase.class);
assertEquals("Verifying the number of registered TestExecutionListeners for DefaultListenersExampleTest.", 3,
testContextManager.getTestExecutionListeners().size());
}
@Test
public void verifyNumNonInheritedDefaultListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(
NonInheritedDefaultListenersExampleTestCase.class);
assertEquals(
"Verifying the number of registered TestExecutionListeners for NonInheritedDefaultListenersExampleTest.",
1, testContextManager.getTestExecutionListeners().size());
}
@Test
public void verifyNumInheritedDefaultListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(InheritedDefaultListenersExampleTestCase.class);
assertEquals(
"Verifying the number of registered TestExecutionListeners for InheritedDefaultListenersExampleTest.", 1,
testContextManager.getTestExecutionListeners().size());
testContextManager = new TestContextManager(SubInheritedDefaultListenersExampleTestCase.class);
assertEquals(
"Verifying the number of registered TestExecutionListeners for SubInheritedDefaultListenersExampleTest.",
1, testContextManager.getTestExecutionListeners().size());
testContextManager = new TestContextManager(SubSubInheritedDefaultListenersExampleTestCase.class);
assertEquals(
"Verifying the number of registered TestExecutionListeners for SubSubInheritedDefaultListenersExampleTest.",
2, testContextManager.getTestExecutionListeners().size());
}
@Test
public void verifyNumListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(ExampleTestCase.class);
assertEquals("Verifying the number of registered TestExecutionListeners for ExampleTest.", 3,
testContextManager.getTestExecutionListeners().size());
}
@Test
public void verifyNumNonInheritedListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(NonInheritedListenersExampleTestCase.class);
assertEquals("Verifying the number of registered TestExecutionListeners for NonInheritedListenersExampleTest.",
1, testContextManager.getTestExecutionListeners().size());
}
@Test
public void verifyNumInheritedListenersRegistered() throws Exception {
TestContextManager testContextManager = new TestContextManager(InheritedListenersExampleTestCase.class);
assertEquals("Verifying the number of registered TestExecutionListeners for InheritedListenersExampleTest.", 4,
testContextManager.getTestExecutionListeners().size());
}
@Test(expected = IllegalStateException.class)
public void verifyDuplicateListenersConfigThrowsException() throws Exception {
new TestContextManager(DuplicateListenersConfigExampleTestCase.class);
}
static class DefaultListenersExampleTestCase {
}
@TestExecutionListeners(QuuxTestExecutionListener.class)
static class InheritedDefaultListenersExampleTestCase extends DefaultListenersExampleTestCase {
}
static class SubInheritedDefaultListenersExampleTestCase extends InheritedDefaultListenersExampleTestCase {
}
@TestExecutionListeners(EnigmaTestExecutionListener.class)
static class SubSubInheritedDefaultListenersExampleTestCase extends SubInheritedDefaultListenersExampleTestCase {
}
@TestExecutionListeners(listeners = { QuuxTestExecutionListener.class }, inheritListeners = false)
static class NonInheritedDefaultListenersExampleTestCase extends InheritedDefaultListenersExampleTestCase {
}
@TestExecutionListeners( { FooTestExecutionListener.class, BarTestExecutionListener.class,
BazTestExecutionListener.class })
static class ExampleTestCase {
}
@TestExecutionListeners(QuuxTestExecutionListener.class)
static class InheritedListenersExampleTestCase extends ExampleTestCase {
}
@TestExecutionListeners(listeners = QuuxTestExecutionListener.class, inheritListeners = false)
static class NonInheritedListenersExampleTestCase extends InheritedListenersExampleTestCase {
}
@TestExecutionListeners(listeners = FooTestExecutionListener.class, value = BarTestExecutionListener.class)
static class DuplicateListenersConfigExampleTestCase {
}
static class FooTestExecutionListener extends AbstractTestExecutionListener {
}
static class BarTestExecutionListener extends AbstractTestExecutionListener {
}
static class BazTestExecutionListener extends AbstractTestExecutionListener {
}
static class QuuxTestExecutionListener extends AbstractTestExecutionListener {
}
static class EnigmaTestExecutionListener extends AbstractTestExecutionListener {
}
}

View File

@@ -0,0 +1,5 @@
dog.(class)=org.springframework.beans.Pet
dog.$0=Fido
testString2.(class)=java.lang.String
testString2.$0=Test String #2

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2009 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.test.context.configuration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.junit4.PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests;
/**
* Integration tests which verify that the same custom {@link ContextLoader} can
* be used at all levels within a test class hierarchy when the
* <code>loader</code> is <i>inherited</i> (i.e., not explicitly declared) via
* {@link ContextConfiguration &#064;ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.0
* @see PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests
* @see ContextConfigurationWithPropertiesExtendingPropertiesTests
*/
@ContextConfiguration
public class ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests extends
PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests {
@Autowired
private Pet dog;
@Autowired
private String testString2;
@Test
public void verifyExtendedAnnotationAutowiredFields() {
assertNotNull("The dog field should have been autowired.", this.dog);
assertEquals("Fido", this.dog.getName());
assertNotNull("The testString2 field should have been autowired.", this.testString2);
assertEquals("Test String #2", this.testString2);
}
}

View File

@@ -0,0 +1,5 @@
dog.(class)=org.springframework.beans.Pet
dog.$0=Fido
testString2.(class)=java.lang.String
testString2.$0=Test String #2

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2009 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.test.context.configuration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.junit4.PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests;
import org.springframework.test.context.support.GenericPropertiesContextLoader;
/**
* Integration tests which verify that the same custom {@link ContextLoader} can
* be used at all levels within a test class hierarchy when the
* <code>loader</code> is explicitly declared via {@link ContextConfiguration
* &#064;ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.0
* @see PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests
* @see ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests
*/
@ContextConfiguration(loader = GenericPropertiesContextLoader.class)
public class ContextConfigurationWithPropertiesExtendingPropertiesTests extends
PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests {
@Autowired
private Pet dog;
@Autowired
private String testString2;
@Test
public void verifyExtendedAnnotationAutowiredFields() {
assertNotNull("The dog field should have been autowired.", this.dog);
assertEquals("Fido", this.dog.getName());
assertNotNull("The testString2 field should have been autowired.", this.testString2);
assertEquals("Test String #2", this.testString2);
}
}

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="user.name">Dave</prop>
<prop key="username">Andy</prop>
</props>
</property>
</bean>
<!-- spr5906 -->
<bean id="derived"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="user.name">#{properties['user.name']}</prop>
<prop key="username">#{properties['username']}</prop>
<prop key="username.no.quotes">#{properties[username]}</prop>
<prop key="username.no.brackets">#{properties.username}</prop>
<prop key="#{properties['user.name']}">exists</prop>
<prop key="#{properties.username}">exists also</prop>
</props>
</property>
</bean>
<!-- spr5847 -->
<bean id="andy"
class="org.springframework.test.context.expression.ExpressionUsageTests$Foo">
<property name="name" value="#{properties.username}" />
</bean>
<bean id="andy2"
class="org.springframework.test.context.expression.ExpressionUsageTests$Foo">
<property name="name" value="#{properties.username }" /><!-- space in expression -->
</bean>
</beans>

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2011 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.test.context.expression;
import static junit.framework.Assert.assertEquals;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Andy Clement
* @author Dave Syer
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ExpressionUsageTests {
@Autowired
@Qualifier("derived")
private Properties props;
@Autowired
@Qualifier("andy2")
private Foo andy2;
@Autowired
@Qualifier("andy")
private Foo andy;
@Test
public void testSpr5906() throws Exception {
// verify the property values have been evaluated as expressions
assertEquals("Dave", props.getProperty("user.name"));
assertEquals("Andy", props.getProperty("username"));
// verify the property keys have been evaluated as expressions
assertEquals("exists", props.getProperty("Dave"));
assertEquals("exists also", props.getProperty("Andy"));
}
@Test
public void testSpr5847() throws Exception {
assertEquals("Andy", andy2.getName());
assertEquals("Andy", andy.getName());
}
public static class Foo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="employee" class="org.springframework.beans.Employee">
<property name="name" value="John Smith" />
<property name="age" value="42" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
<bean id="pet" class="org.springframework.beans.Pet">
<constructor-arg value="Fido" />
</bean>
<bean id="foo" class="java.lang.String">
<constructor-arg value="Foo" />
</bean>
<bean id="bar" class="java.lang.String">
<constructor-arg value="Bar" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.ConcreteTransactionalJUnit4SpringContextTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,229 @@
/*
* 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.test.context.junit38;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.RunWith;
import org.springframework.beans.Employee;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.ExpectedException;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;
/**
* Combined integration test for {@link AbstractJUnit38SpringContextTests} and
* {@link AbstractTransactionalJUnit38SpringContextTests}.
*
* @author Sam Brannen
* @since 2.5
*/
@SuppressWarnings("deprecation")
@RunWith(JUnit38ClassRunner.class)
@ContextConfiguration
public class ConcreteTransactionalJUnit38SpringContextTests extends AbstractTransactionalJUnit38SpringContextTests
implements BeanNameAware, InitializingBean {
protected static final String BOB = "bob";
protected static final String JANE = "jane";
protected static final String SUE = "sue";
protected static final String YODA = "yoda";
private boolean beanInitialized = false;
private String beanName = "replace me with [" + getClass().getName() + "]";
private Employee employee;
@Autowired
private Pet pet;
@Autowired(required = false)
protected Long nonrequiredLong;
@Resource()
protected String foo;
protected String bar;
private boolean inTransaction = false;
public ConcreteTransactionalJUnit38SpringContextTests() throws Exception {
this(null);
}
public ConcreteTransactionalJUnit38SpringContextTests(final String name) throws Exception {
super(name);
}
protected static int clearPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.deleteFromTables(simpleJdbcTemplate, "person");
}
protected static void createPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
try {
simpleJdbcTemplate.update("CREATE TABLE person (name VARCHAR(20) NOT NULL, PRIMARY KEY(name))");
}
catch (final BadSqlGrammarException bsge) {
/* ignore */
}
}
protected static int countRowsInPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.countRowsInTable(simpleJdbcTemplate, "person");
}
protected static int addPerson(final SimpleJdbcTemplate simpleJdbcTemplate, final String name) {
return simpleJdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
protected static int deletePerson(final SimpleJdbcTemplate simpleJdbcTemplate, final String name) {
return simpleJdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
public final void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
public final void setBeanName(final String beanName) {
this.beanName = beanName;
}
@Autowired
protected final void setEmployee(final Employee employee) {
this.employee = employee;
}
@Resource
protected final void setBar(final String bar) {
this.bar = bar;
}
@NotTransactional
@Timed(millis = 10000)
public void testNoOpShouldNotTimeOut() throws Exception {
/* no-op */
}
@NotTransactional
@ExpectedException(IndexOutOfBoundsException.class)
public void testExpectedExceptionAnnotation() {
new ArrayList<Object>().get(1);
}
@NotTransactional
public void testApplicationContextSet() {
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.",
super.applicationContext);
}
@NotTransactional
public void testBeanInitialized() {
assertTrue("This test bean should have been initialized due to InitializingBean semantics.",
this.beanInitialized);
}
@NotTransactional
public void testBeanNameSet() {
assertEquals("The bean name of this test instance should have been set to the fully qualified class name "
+ "due to BeanNameAware semantics.", getClass().getName(), this.beanName);
}
@NotTransactional
public void testAnnotationAutowiredFields() {
assertNull("The nonrequiredLong property should NOT have been autowired.", this.nonrequiredLong);
assertNotNull("The pet field should have been autowired.", this.pet);
assertEquals("Fido", this.pet.getName());
}
@NotTransactional
public void testAnnotationAutowiredMethods() {
assertNotNull("The employee setter method should have been autowired.", this.employee);
assertEquals("John Smith", this.employee.getName());
}
@NotTransactional
public void testResourceAnnotationWiredFields() {
assertEquals("The foo field should have been wired via @Resource.", "Foo", this.foo);
}
@NotTransactional
public void testResourceAnnotationWiredMethods() {
assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar);
}
@BeforeTransaction
public void beforeTransaction() {
this.inTransaction = true;
assertEquals("Verifying the number of rows in the person table before a transactional test method.", 1,
countRowsInPersonTable(super.simpleJdbcTemplate));
assertEquals("Adding yoda", 1, addPerson(super.simpleJdbcTemplate, YODA));
}
@Override
public void setUp() throws Exception {
assertEquals("Verifying the number of rows in the person table before a test method.", (this.inTransaction ? 2
: 1), countRowsInPersonTable(super.simpleJdbcTemplate));
}
public void testModifyTestDataWithinTransaction() {
assertEquals("Adding jane", 1, addPerson(super.simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(super.simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within transactionalMethod2().", 4,
countRowsInPersonTable(super.simpleJdbcTemplate));
}
@Override
public void tearDown() throws Exception {
assertEquals("Verifying the number of rows in the person table after a test method.", (this.inTransaction ? 4
: 1), countRowsInPersonTable(super.simpleJdbcTemplate));
}
@AfterTransaction
public void afterTransaction() {
assertEquals("Deleting yoda", 1, deletePerson(super.simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table after a transactional test method.", 1,
countRowsInPersonTable(super.simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Autowired
void setDataSource(final DataSource dataSource) {
final SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
clearPersonTable(simpleJdbcTemplate);
addPerson(simpleJdbcTemplate, BOB);
}
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
</beans>

View File

@@ -0,0 +1,153 @@
/*
* 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.test.context.junit38;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import junit.framework.TestCase;
import junit.framework.TestResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
/**
* <p>
* JUnit 4 based integration test for verifying that '<em>before</em>' and '<em>after</em>'
* methods of {@link TestExecutionListener TestExecutionListeners} as well as
* {@link BeforeTransaction @BeforeTransaction} and
* {@link AfterTransaction @AfterTransaction} methods can fail a test in a JUnit
* 3.8 environment, as requested in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-3960"
* target="_blank">SPR-3960</a>.
* </p>
*
* @author Sam Brannen
* @since 2.5
*/
@RunWith(Parameterized.class)
public class FailingBeforeAndAfterMethodsTests {
protected final Class<?> clazz;
public FailingBeforeAndAfterMethodsTests(final Class<?> clazz) {
this.clazz = clazz;
}
@Parameters
public static Collection<Object[]> testData() {
return Arrays.asList(new Object[][] {
{ AlwaysFailingBeforeTestMethodTestCase.class },
{ AlwaysFailingAfterTestMethodTestCase.class },
{ FailingBeforeTransactionalTestCase.class },
{ FailingAfterTransactionalTestCase.class }
});
}
@Test
public void runTestAndAssertCounters() throws Exception {
final String testName = "testNothing";
final TestCase testCase = (TestCase) this.clazz.newInstance();
testCase.setName(testName);
TestResult testResult = testCase.run();
assertEquals("Verifying number of errors for test method [" + testName + "] and class [" + this.clazz + "].",
0, testResult.errorCount());
assertEquals("Verifying number of failures for test method [" + testName + "] and class [" + this.clazz + "].",
1, testResult.failureCount());
}
static class AlwaysFailingBeforeTestMethodTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) {
junit.framework.Assert.fail("always failing beforeTestMethod()");
}
}
static class AlwaysFailingAfterTestMethodTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) {
junit.framework.Assert.fail("always failing afterTestMethod()");
}
}
@org.junit.Ignore
@SuppressWarnings("deprecation")
@TestExecutionListeners(listeners = AlwaysFailingBeforeTestMethodTestExecutionListener.class, inheritListeners = false)
public static class AlwaysFailingBeforeTestMethodTestCase extends AbstractJUnit38SpringContextTests {
public void testNothing() {
}
}
@org.junit.Ignore
@SuppressWarnings("deprecation")
@TestExecutionListeners(listeners = AlwaysFailingAfterTestMethodTestExecutionListener.class, inheritListeners = false)
public static class AlwaysFailingAfterTestMethodTestCase extends AbstractJUnit38SpringContextTests {
public void testNothing() {
}
}
@org.junit.Ignore
@SuppressWarnings("deprecation")
@ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml")
public static class FailingBeforeTransactionalTestCase extends AbstractTransactionalJUnit38SpringContextTests {
public void testNothing() {
}
@BeforeTransaction
public void beforeTransaction() {
fail("always failing beforeTransaction()");
}
}
@org.junit.Ignore
@SuppressWarnings("deprecation")
@ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml")
public static class FailingAfterTransactionalTestCase extends AbstractTransactionalJUnit38SpringContextTests {
public void testNothing() {
}
@AfterTransaction
public void afterTransaction() {
fail("always failing afterTransaction()");
}
}
}

View File

@@ -0,0 +1,211 @@
/*
* Copyright 2002-2009 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.test.context.junit38;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import junit.framework.TestResult;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.annotation.ProfileValueSource;
import org.springframework.test.annotation.ProfileValueSourceConfiguration;
import org.springframework.test.annotation.SystemProfileValueSource;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies proper handling of {@link IfProfileValue &#064;IfProfileValue} and
* {@link ProfileValueSourceConfiguration &#064;ProfileValueSourceConfiguration}
* in conjunction with {@link AbstractJUnit38SpringContextTests}.
*
* @author Sam Brannen
* @since 2.5
*/
public class ProfileValueJUnit38SpringContextTests extends TestCase {
private static final String EMPTY = "testIfProfileValueEmpty";
private static final String DISABLED_VIA_WRONG_NAME = "testIfProfileValueDisabledViaWrongName";
private static final String DISABLED_VIA_WRONG_VALUE = "testIfProfileValueDisabledViaWrongValue";
private static final String ENABLED_VIA_MULTIPLE_VALUES = "testIfProfileValueEnabledViaMultipleValues";
private static final String ENABLED_VIA_SINGLE_VALUE = "testIfProfileValueEnabledViaSingleValue";
private static final String NOT_CONFIGURED = "testIfProfileValueNotConfigured";
private static final String NAME = "ProfileValueAnnotationAwareTransactionalTests.profile_value.name";
private static final String VALUE = "enigma";
private final Map<String, Integer> expectedInvocationCounts = new HashMap<String, Integer>();
public ProfileValueJUnit38SpringContextTests() {
System.setProperty(NAME, VALUE);
}
@Override
protected void setUp() throws Exception {
this.expectedInvocationCounts.put(EMPTY, 0);
this.expectedInvocationCounts.put(DISABLED_VIA_WRONG_NAME, 0);
this.expectedInvocationCounts.put(DISABLED_VIA_WRONG_VALUE, 0);
this.expectedInvocationCounts.put(ENABLED_VIA_SINGLE_VALUE, 1);
this.expectedInvocationCounts.put(ENABLED_VIA_MULTIPLE_VALUES, 1);
this.expectedInvocationCounts.put(NOT_CONFIGURED, 1);
}
private void configureDisabledClassExpectations() {
this.expectedInvocationCounts.put(ENABLED_VIA_SINGLE_VALUE, 0);
this.expectedInvocationCounts.put(ENABLED_VIA_MULTIPLE_VALUES, 0);
this.expectedInvocationCounts.put(NOT_CONFIGURED, 0);
}
private void runTestAndAssertCounters(Class<? extends DefaultProfileValueSourceTestCase> testCaseType,
String testName, int expectedInvocationCount, int expectedErrorCount, int expectedFailureCount)
throws Exception {
DefaultProfileValueSourceTestCase testCase = testCaseType.newInstance();
testCase.setName(testName);
TestResult testResult = testCase.run();
assertEquals("Verifying number of invocations for test method [" + testName + "].", expectedInvocationCount,
testCase.invocationCount);
assertEquals("Verifying number of errors for test method [" + testName + "].", expectedErrorCount,
testResult.errorCount());
assertEquals("Verifying number of failures for test method [" + testName + "].", expectedFailureCount,
testResult.failureCount());
}
private void runTests(final Class<? extends DefaultProfileValueSourceTestCase> testCaseType) throws Exception {
runTestAndAssertCounters(testCaseType, EMPTY, expectedInvocationCounts.get(EMPTY), 0, 0);
runTestAndAssertCounters(testCaseType, DISABLED_VIA_WRONG_NAME,
expectedInvocationCounts.get(DISABLED_VIA_WRONG_NAME), 0, 0);
runTestAndAssertCounters(testCaseType, DISABLED_VIA_WRONG_VALUE,
expectedInvocationCounts.get(DISABLED_VIA_WRONG_VALUE), 0, 0);
runTestAndAssertCounters(testCaseType, ENABLED_VIA_SINGLE_VALUE,
expectedInvocationCounts.get(ENABLED_VIA_SINGLE_VALUE), 0, 0);
runTestAndAssertCounters(testCaseType, ENABLED_VIA_MULTIPLE_VALUES,
expectedInvocationCounts.get(ENABLED_VIA_MULTIPLE_VALUES), 0, 0);
runTestAndAssertCounters(testCaseType, NOT_CONFIGURED, expectedInvocationCounts.get(NOT_CONFIGURED), 0, 0);
}
public void testDefaultProfileValueSource() throws Exception {
assertEquals("Verifying the type of the configured ProfileValueSource.", SystemProfileValueSource.class,
new DefaultProfileValueSourceTestCase().getProfileValueSource().getClass());
runTests(DefaultProfileValueSourceTestCase.class);
}
public void testHardCodedProfileValueSource() throws Exception {
assertEquals("Verifying the type of the configured ProfileValueSource.", HardCodedProfileValueSource.class,
new HardCodedProfileValueSourceTestCase().getProfileValueSource().getClass());
runTests(HardCodedProfileValueSourceTestCase.class);
}
public void testClassLevelIfProfileValueEnabledSingleValue() throws Exception {
runTests(ClassLevelIfProfileValueEnabledSingleValueTestCase.class);
}
public void testClassLevelIfProfileValueDisabledSingleValue() throws Exception {
configureDisabledClassExpectations();
runTests(ClassLevelIfProfileValueDisabledSingleValueTestCase.class);
}
public void testClassLevelIfProfileValueEnabledMultiValue() throws Exception {
runTests(ClassLevelIfProfileValueEnabledMultiValueTestCase.class);
}
public void testClassLevelIfProfileValueDisabledMultiValue() throws Exception {
configureDisabledClassExpectations();
runTests(ClassLevelIfProfileValueDisabledMultiValueTestCase.class);
}
// -------------------------------------------------------------------
/**
* Note that {@link TestExecutionListeners @TestExecutionListeners} is
* explicitly configured with an empty list, thus disabling all default
* listeners.
*/
@SuppressWarnings("deprecation")
@TestExecutionListeners(listeners = {}, inheritListeners = false)
public static class DefaultProfileValueSourceTestCase extends AbstractJUnit38SpringContextTests {
int invocationCount = 0;
public ProfileValueSource getProfileValueSource() {
return super.profileValueSource;
}
@IfProfileValue(name = NAME, value = "")
public void testIfProfileValueEmpty() {
this.invocationCount++;
fail("An empty profile value should throw an IllegalArgumentException.");
}
@IfProfileValue(name = NAME + "X", value = VALUE)
public void testIfProfileValueDisabledViaWrongName() {
this.invocationCount++;
fail("The body of a disabled test should never be executed!");
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public void testIfProfileValueDisabledViaWrongValue() {
this.invocationCount++;
fail("The body of a disabled test should never be executed!");
}
@IfProfileValue(name = NAME, value = VALUE)
public void testIfProfileValueEnabledViaSingleValue() {
this.invocationCount++;
}
@IfProfileValue(name = NAME, values = { "foo", VALUE, "bar" })
public void testIfProfileValueEnabledViaMultipleValues() {
this.invocationCount++;
}
public void testIfProfileValueNotConfigured() {
this.invocationCount++;
}
}
@ProfileValueSourceConfiguration(HardCodedProfileValueSource.class)
public static class HardCodedProfileValueSourceTestCase extends DefaultProfileValueSourceTestCase {
}
public static class HardCodedProfileValueSource implements ProfileValueSource {
public String get(final String key) {
return (key.equals(NAME) ? VALUE : null);
}
}
@IfProfileValue(name = NAME, value = VALUE)
public static class ClassLevelIfProfileValueEnabledSingleValueTestCase extends DefaultProfileValueSourceTestCase {
}
@IfProfileValue(name = NAME, value = VALUE + "X")
public static class ClassLevelIfProfileValueDisabledSingleValueTestCase extends DefaultProfileValueSourceTestCase {
}
@IfProfileValue(name = NAME, values = { "foo", VALUE, "bar" })
public static class ClassLevelIfProfileValueEnabledMultiValueTestCase extends DefaultProfileValueSourceTestCase {
}
@IfProfileValue(name = NAME, values = { "foo", "bar", "baz" })
public static class ClassLevelIfProfileValueDisabledMultiValueTestCase extends DefaultProfileValueSourceTestCase {
}
}

View File

@@ -0,0 +1,97 @@
/*
* 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.test.context.junit38;
import junit.framework.TestCase;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.TestExecutionListeners;
/**
* Unit test for {@link AbstractJUnit38SpringContextTests} which focuses on
* proper support of the {@link Repeat @Repeat} annotation.
*
* @author Sam Brannen
* @since 2.5
*/
public class RepeatedJUnit38SpringContextTests extends TestCase {
public RepeatedJUnit38SpringContextTests() throws Exception {
super();
}
public RepeatedJUnit38SpringContextTests(final String name) throws Exception {
super(name);
}
private void assertRepetitions(final String testName, final int expectedNumInvocations) throws Exception {
final RepeatedTestCase repeatedTestCase = new RepeatedTestCase(testName);
repeatedTestCase.run();
assertEquals("Verifying number of invocations for test method [" + testName + "].", expectedNumInvocations,
repeatedTestCase.invocationCount);
}
public void testRepeatAnnotationSupport() throws Exception {
assertRepetitions("testNonAnnotated", 1);
assertRepetitions("testNegativeRepeatValue", 1);
assertRepetitions("testDefaultRepeatValue", 1);
assertRepetitions("testRepeatedFiveTimes", 5);
}
/**
* Note that {@link TestExecutionListeners @TestExecutionListeners} is
* explicitly configured with an empty list, thus disabling all default
* listeners.
*/
@org.junit.Ignore // causes https://gist.github.com/1165825
@SuppressWarnings("deprecation")
@TestExecutionListeners(listeners = {}, inheritListeners = false)
protected static class RepeatedTestCase extends AbstractJUnit38SpringContextTests {
int invocationCount = 0;
public RepeatedTestCase(final String name) throws Exception {
super(name);
}
@Override
protected void setUp() throws Exception {
this.invocationCount++;
}
public void testNonAnnotated() {
/* no-op */
}
@Repeat(-5)
public void testNegativeRepeatValue() {
/* no-op */
}
@Repeat
public void testDefaultRepeatValue() {
/* no-op */
}
@Repeat(5)
public void testRepeatedFiveTimes() {
/* no-op */
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
/**
* Extension of {@link SpringJUnit4ClassRunnerAppCtxTests}, which verifies that
* we can specify an explicit, <em>absolute path</em> location for our
* application context.
*
* @author Sam Brannen
* @since 2.5
* @see SpringJUnit4ClassRunnerAppCtxTests
* @see ClassPathResourceSpringJUnit4ClassRunnerAppCtxTests
* @see RelativePathSpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { SpringJUnit4ClassRunnerAppCtxTests.DEFAULT_CONTEXT_RESOURCE_PATH }, inheritLocations = false)
public class AbsolutePathSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* Abstract base class for verifying support of Spring's {@link Transactional
* &#64;Transactional} and {@link NotTransactional &#64;NotTransactional}
* annotations.
*
* @author Sam Brannen
* @since 2.5
* @see ClassLevelTransactionalSpringRunnerTests
* @see MethodLevelTransactionalSpringRunnerTests
* @see Transactional
* @see NotTransactional
*/
@SuppressWarnings("deprecation")
@ContextConfiguration("transactionalTests-context.xml")
public abstract class AbstractTransactionalSpringRunnerTests {
protected static final String BOB = "bob";
protected static final String JANE = "jane";
protected static final String SUE = "sue";
protected static final String LUKE = "luke";
protected static final String LEIA = "leia";
protected static final String YODA = "yoda";
protected static int clearPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return simpleJdbcTemplate.update("DELETE FROM person");
}
protected static void createPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
try {
simpleJdbcTemplate.update("CREATE TABLE person (name VARCHAR(20) NOT NULL, PRIMARY KEY(name))");
}
catch (BadSqlGrammarException bsge) {
// ignore
}
}
protected static int countRowsInPersonTable(SimpleJdbcTemplate simpleJdbcTemplate) {
return simpleJdbcTemplate.queryForInt("SELECT COUNT(0) FROM person");
}
protected static int addPerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
protected static int deletePerson(SimpleJdbcTemplate simpleJdbcTemplate, String name) {
return simpleJdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.BeforeAndAfterTransactionAnnotationTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
/**
* JUnit 4 based integration test which verifies
* {@link BeforeTransaction @BeforeTransaction} and
* {@link AfterTransaction @AfterTransaction} behavior.
*
* @author Sam Brannen
* @since 2.5
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({ TransactionalTestExecutionListener.class })
public class BeforeAndAfterTransactionAnnotationTests extends AbstractTransactionalSpringRunnerTests {
protected static SimpleJdbcTemplate simpleJdbcTemplate;
protected static int numBeforeTransactionCalls = 0;
protected static int numAfterTransactionCalls = 0;
protected boolean inTransaction = false;
@BeforeClass
public static void beforeClass() {
BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls = 0;
BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls = 0;
}
@AfterClass
public static void afterClass() {
assertEquals("Verifying the final number of rows in the person table after all tests.", 3,
countRowsInPersonTable(simpleJdbcTemplate));
assertEquals("Verifying the total number of calls to beforeTransaction().", 2,
BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls);
assertEquals("Verifying the total number of calls to afterTransaction().", 2,
BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls);
}
@BeforeTransaction
public void beforeTransaction() {
assertInTransaction(false);
this.inTransaction = true;
BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls++;
clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding yoda", 1, addPerson(simpleJdbcTemplate, YODA));
}
@AfterTransaction
public void afterTransaction() {
assertInTransaction(false);
this.inTransaction = false;
BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls++;
assertEquals("Deleting yoda", 1, deletePerson(simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table after a transactional test method.", 0,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void before() {
assertEquals("Verifying the number of rows in the person table before a test method.", (this.inTransaction ? 1
: 0), countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@Transactional
public void transactionalMethod1() {
assertInTransaction(true);
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Verifying the number of rows in the person table within transactionalMethod1().", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@Transactional
public void transactionalMethod2() {
assertInTransaction(true);
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within transactionalMethod2().", 3,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
public void nonTransactionalMethod() {
assertInTransaction(false);
assertEquals("Adding luke", 1, addPerson(simpleJdbcTemplate, LUKE));
assertEquals("Adding leia", 1, addPerson(simpleJdbcTemplate, LEIA));
assertEquals("Adding yoda", 1, addPerson(simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table without a transaction.", 3,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
/**
* @author Juergen Hoeller
* @author Sam Brannen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(ClassLevelDisabledSpringRunnerTests.CustomTestExecutionListener.class)
@IfProfileValue(name = "ClassLevelDisabledSpringRunnerTests.profile_value.name", value = "enigmaX")
public class ClassLevelDisabledSpringRunnerTests {
@Test
public void testIfProfileValueDisabled() {
fail("The body of a disabled test should never be executed!");
}
public static class CustomTestExecutionListener implements TestExecutionListener {
public void beforeTestClass(TestContext testContext) throws Exception {
fail("A listener method for a disabled test should never be executed!");
}
public void prepareTestInstance(TestContext testContext) throws Exception {
fail("A listener method for a disabled test should never be executed!");
}
public void beforeTestMethod(TestContext testContext) throws Exception {
fail("A listener method for a disabled test should never be executed!");
}
public void afterTestMethod(TestContext testContext) throws Exception {
fail("A listener method for a disabled test should never be executed!");
}
public void afterTestClass(TestContext testContext) throws Exception {
fail("A listener method for a disabled test should never be executed!");
}
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.ClassLevelTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* JUnit 4 based integration test which verifies support of Spring's
* {@link Transactional &#64;Transactional}, {@link NotTransactional
* &#64;NotTransactional}, {@link TestExecutionListeners
* &#64;TestExecutionListeners}, and {@link ContextConfiguration
* &#64;ContextConfiguration} annotations in conjunction with the
* {@link SpringJUnit4ClassRunner} and the following
* {@link TestExecutionListener TestExecutionListeners}:
* </p>
* <ul>
* <li>{@link DependencyInjectionTestExecutionListener}</li>
* <li>{@link DirtiesContextTestExecutionListener}</li>
* <li>{@link TransactionalTestExecutionListener}</li>
* </ul>
* <p>
* This class specifically tests usage of <code>&#064;Transactional</code>
* defined at the <strong>class level</strong>.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see MethodLevelTransactionalSpringRunnerTests
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@Transactional
public class ClassLevelTransactionalSpringRunnerTests extends AbstractTransactionalSpringRunnerTests {
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", 4,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void verifyInitialTestData() {
clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Deleting bob", 1, deletePerson(simpleJdbcTemplate, BOB));
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@NotTransactional
public void modifyTestDataWithoutTransaction() {
assertInTransaction(false);
assertEquals("Adding luke", 1, addPerson(simpleJdbcTemplate, LUKE));
assertEquals("Adding leia", 1, addPerson(simpleJdbcTemplate, LEIA));
assertEquals("Adding yoda", 1, addPerson(simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table without a transaction.", 4,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.ResourceUtils;
/**
* Extension of {@link SpringJUnit4ClassRunnerAppCtxTests}, which verifies that
* we can specify an explicit, <em>classpath</em> location for our application
* context.
*
* @author Sam Brannen
* @since 2.5
* @see SpringJUnit4ClassRunnerAppCtxTests
* @see #CLASSPATH_CONTEXT_RESOURCE_PATH
* @see AbsolutePathSpringJUnit4ClassRunnerAppCtxTests
* @see RelativePathSpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { ClassPathResourceSpringJUnit4ClassRunnerAppCtxTests.CLASSPATH_CONTEXT_RESOURCE_PATH })
public class ClassPathResourceSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/**
* Classpath-based resource path for the application context configuration
* for {@link SpringJUnit4ClassRunnerAppCtxTests}:
* <code>&quot;classpath:/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml&quot;</code>
*
* @see SpringJUnit4ClassRunnerAppCtxTests#DEFAULT_CONTEXT_RESOURCE_PATH
* @see ResourceUtils#CLASSPATH_URL_PREFIX
*/
public static final String CLASSPATH_CONTEXT_RESOURCE_PATH = ResourceUtils.CLASSPATH_URL_PREFIX
+ SpringJUnit4ClassRunnerAppCtxTests.DEFAULT_CONTEXT_RESOURCE_PATH;
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<import resource="transactionalTests-context.xml" />
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.ConcreteTransactionalJUnit4SpringContextTests$DatabaseSetup" />
<bean id="employee" class="org.springframework.beans.Employee">
<property name="name" value="John Smith" />
<property name="age" value="42" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
<bean id="pet" class="org.springframework.beans.Pet">
<constructor-arg value="Fido" />
</bean>
<bean id="foo" class="java.lang.String">
<constructor-arg value="Foo" />
</bean>
<bean id="bar" class="java.lang.String">
<constructor-arg value="Bar" />
</bean>
</beans>

View File

@@ -0,0 +1,232 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import static org.springframework.test.transaction.TransactionTestUtils.inTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.Employee;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;
/**
* Combined integration test for {@link AbstractJUnit4SpringContextTests} and
* {@link AbstractTransactionalJUnit4SpringContextTests}.
*
* @author Sam Brannen
* @since 2.5
*/
@SuppressWarnings("deprecation")
@ContextConfiguration
public class ConcreteTransactionalJUnit4SpringContextTests extends AbstractTransactionalJUnit4SpringContextTests
implements BeanNameAware, InitializingBean {
protected static final String BOB = "bob";
protected static final String JANE = "jane";
protected static final String SUE = "sue";
protected static final String LUKE = "luke";
protected static final String LEIA = "leia";
protected static final String YODA = "yoda";
private boolean beanInitialized = false;
private String beanName = "replace me with [" + getClass().getName() + "]";
private Employee employee;
@Autowired
private Pet pet;
@Autowired(required = false)
protected Long nonrequiredLong;
@Resource
protected String foo;
protected String bar;
protected static int clearPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.deleteFromTables(simpleJdbcTemplate, "person");
}
protected static void createPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
try {
simpleJdbcTemplate.update("CREATE TABLE person (name VARCHAR(20) NOT NULL, PRIMARY KEY(name))");
}
catch (final BadSqlGrammarException bsge) {
/* ignore */
}
}
protected static int countRowsInPersonTable(final SimpleJdbcTemplate simpleJdbcTemplate) {
return SimpleJdbcTestUtils.countRowsInTable(simpleJdbcTemplate, "person");
}
protected static int addPerson(final SimpleJdbcTemplate simpleJdbcTemplate, final String name) {
return simpleJdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
protected static int deletePerson(final SimpleJdbcTemplate simpleJdbcTemplate, final String name) {
return simpleJdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
@Resource
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
}
@Autowired
protected final void setEmployee(final Employee employee) {
this.employee = employee;
}
@Resource
protected final void setBar(final String bar) {
this.bar = bar;
}
public final void setBeanName(final String beanName) {
this.beanName = beanName;
}
public final void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
@Test
@NotTransactional
public final void verifyApplicationContext() {
assertInTransaction(false);
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.",
super.applicationContext);
}
@Test
@NotTransactional
public final void verifyBeanInitialized() {
assertInTransaction(false);
assertTrue("This test bean should have been initialized due to InitializingBean semantics.",
this.beanInitialized);
}
@Test
@NotTransactional
public final void verifyBeanNameSet() {
assertInTransaction(false);
assertEquals("The bean name of this test instance should have been set to the fully qualified class name "
+ "due to BeanNameAware semantics.", getClass().getName(), this.beanName);
}
@Test
@NotTransactional
public final void verifyAnnotationAutowiredFields() {
assertInTransaction(false);
assertNull("The nonrequiredLong property should NOT have been autowired.", this.nonrequiredLong);
assertNotNull("The pet field should have been autowired.", this.pet);
assertEquals("Fido", this.pet.getName());
}
@Test
@NotTransactional
public final void verifyAnnotationAutowiredMethods() {
assertInTransaction(false);
assertNotNull("The employee setter method should have been autowired.", this.employee);
assertEquals("John Smith", this.employee.getName());
}
@Test
@NotTransactional
public final void verifyResourceAnnotationWiredFields() {
assertInTransaction(false);
assertEquals("The foo field should have been wired via @Resource.", "Foo", this.foo);
}
@Test
@NotTransactional
public final void verifyResourceAnnotationWiredMethods() {
assertInTransaction(false);
assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar);
}
@BeforeTransaction
public void beforeTransaction() {
assertEquals("Verifying the number of rows in the person table before a transactional test method.", 1,
countRowsInPersonTable(super.simpleJdbcTemplate));
assertEquals("Adding yoda", 1, addPerson(super.simpleJdbcTemplate, YODA));
}
@Before
public void setUp() throws Exception {
assertEquals("Verifying the number of rows in the person table before a test method.",
(inTransaction() ? 2 : 1), countRowsInPersonTable(super.simpleJdbcTemplate));
}
@Test
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Adding jane", 1, addPerson(super.simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(super.simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table in modifyTestDataWithinTransaction().", 4,
countRowsInPersonTable(super.simpleJdbcTemplate));
}
@After
public void tearDown() throws Exception {
assertEquals("Verifying the number of rows in the person table after a test method.",
(inTransaction() ? 4 : 1), countRowsInPersonTable(super.simpleJdbcTemplate));
}
@AfterTransaction
public void afterTransaction() {
assertEquals("Deleting yoda", 1, deletePerson(super.simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table after a transactional test method.", 1,
countRowsInPersonTable(super.simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
clearPersonTable(simpleJdbcTemplate);
addPerson(simpleJdbcTemplate, BOB);
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.model.InitializationError;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.GenericPropertiesContextLoader;
/**
* Integration tests which verify that a subclass of {@link SpringJUnit4ClassRunner}
* can specify a custom <em>default ContextLoader class name</em> that overrides
* the standard default class name.
*
* @author Sam Brannen
* @since 3.0
*/
@RunWith(CustomDefaultContextLoaderClassSpringRunnerTests.PropertiesBasedSpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties")
public class CustomDefaultContextLoaderClassSpringRunnerTests {
@Autowired
private Pet cat;
@Autowired
private String testString;
@Test
public void verifyAnnotationAutowiredFields() {
assertNotNull("The cat field should have been autowired.", this.cat);
assertEquals("Garfield", this.cat.getName());
assertNotNull("The testString field should have been autowired.", this.testString);
assertEquals("Test String", this.testString);
}
public static final class PropertiesBasedSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner {
public PropertiesBasedSpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
@Override
protected String getDefaultContextLoaderClassName(Class<?> clazz) {
return GenericPropertiesContextLoader.class.getName();
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="txMgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.DefaultRollbackFalseTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,91 @@
/*
* 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* JUnit 4 based integration test which verifies proper transactional behavior when the
* {@link TransactionConfiguration#defaultRollback() defaultRollback} attribute
* of the {@link TransactionConfiguration} annotation is set to <strong><code>false</code></strong>.
* Also tests configuration of the
* {@link TransactionConfiguration#transactionManager() transaction manager name}.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see TransactionConfiguration
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(transactionManager = "txMgr", defaultRollback = false)
@Transactional
public class DefaultRollbackFalseTransactionalSpringRunnerTests extends AbstractTransactionalSpringRunnerTests {
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void verifyInitialTestData() {
clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Deleting bob", 1, deletePerson(simpleJdbcTemplate, BOB));
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.DefaultRollbackTrueTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* JUnit 4 based integration test which verifies proper transactional behavior when the
* {@link TransactionConfiguration#defaultRollback() defaultRollback} attribute
* of the {@link TransactionConfiguration} annotation is set to <strong><code>true</code></strong>.
*
* @author Sam Brannen
* @since 2.5
* @see TransactionConfiguration
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(defaultRollback = true)
public class DefaultRollbackTrueTransactionalSpringRunnerTests extends AbstractTransactionalSpringRunnerTests {
protected static int originalNumRows;
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", originalNumRows,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void verifyInitialTestData() {
originalNumRows = clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test(timeout = 1000)
@Transactional
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 3,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.annotation.ProfileValueSource;
import org.springframework.test.annotation.ProfileValueSourceConfiguration;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies proper handling of JUnit's {@link Ignore &#064;Ignore} and Spring's
* {@link IfProfileValue &#064;IfProfileValue} and
* {@link ProfileValueSourceConfiguration &#064;ProfileValueSourceConfiguration}
* (with the <em>implicit, default {@link ProfileValueSource}</em>) annotations in
* conjunction with the {@link SpringJUnit4ClassRunner}.
* <p>
* Note that {@link TestExecutionListeners &#064;TestExecutionListeners} is
* explicitly configured with an empty list, thus disabling all default
* listeners.
*
* @author Sam Brannen
* @since 2.5
* @see HardCodedProfileValueSourceSpringRunnerTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {})
public class EnabledAndIgnoredSpringRunnerTests {
protected static final String NAME = "EnabledAndIgnoredSpringRunnerTests.profile_value.name";
protected static final String VALUE = "enigma";
protected static int numTestsExecuted = 0;
@BeforeClass
public static void setProfileValue() {
numTestsExecuted = 0;
System.setProperty(NAME, VALUE);
}
@AfterClass
public static void verifyNumTestsExecuted() {
assertEquals("Verifying the number of tests executed.", 3, numTestsExecuted);
}
@Test
@IfProfileValue(name = NAME, value = VALUE + "X")
public void testIfProfileValueDisabled() {
numTestsExecuted++;
fail("The body of a disabled test should never be executed!");
}
@Test
@IfProfileValue(name = NAME, value = VALUE)
public void testIfProfileValueEnabledViaSingleValue() {
numTestsExecuted++;
}
@Test
@IfProfileValue(name = NAME, values = { "foo", VALUE, "bar" })
public void testIfProfileValueEnabledViaMultipleValues() {
numTestsExecuted++;
}
@Test
public void testIfProfileValueNotConfigured() {
numTestsExecuted++;
}
@Test
@Ignore
public void testJUnitIgnoreAnnotation() {
numTestsExecuted++;
fail("The body of an ignored test should never be executed!");
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2011 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.springframework.test.annotation.ExpectedException;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies proper handling of the following in conjunction with the
* {@link SpringJUnit4ClassRunner}:
* <ul>
* <li>JUnit's {@link Test#expected() &#064;Test(expected=...)}</li>
* <li>Spring's {@link ExpectedException &#064;ExpectedException}</li>
* </ul>
*
* @author Sam Brannen
* @since 3.0
*/
@SuppressWarnings("deprecation")
@RunWith(JUnit4.class)
public class ExpectedExceptionSpringRunnerTests {
@Test
public void expectedExceptions() throws Exception {
Class<ExpectedExceptionSpringRunnerTestCase> testClass = ExpectedExceptionSpringRunnerTestCase.class;
TrackingRunListener listener = new TrackingRunListener();
RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
new SpringJUnit4ClassRunner(testClass).run(notifier);
assertEquals("Verifying number of failures for test class [" + testClass + "].", 1,
listener.getTestFailureCount());
assertEquals("Verifying number of tests started for test class [" + testClass + "].", 3,
listener.getTestStartedCount());
assertEquals("Verifying number of tests finished for test class [" + testClass + "].", 3,
listener.getTestFinishedCount());
}
@org.junit.Ignore
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public static final class ExpectedExceptionSpringRunnerTestCase {
// Should Pass.
@Test(expected = IndexOutOfBoundsException.class)
public void verifyJUnitExpectedException() {
new ArrayList<Object>().get(1);
}
// Should Pass.
@Test
@ExpectedException(IndexOutOfBoundsException.class)
public void verifySpringExpectedException() {
new ArrayList<Object>().get(1);
}
// Should Fail due to duplicate configuration.
@Test(expected = IllegalStateException.class)
@ExpectedException(IllegalStateException.class)
public void verifyJUnitAndSpringExpectedException() {
new ArrayList<Object>().get(1);
}
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
</beans>

View File

@@ -0,0 +1,202 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
/**
* <p>
* JUnit 4 based integration test for verifying that '<i>before</i>' and '<i>after</i>'
* methods of {@link TestExecutionListener TestExecutionListeners} as well as
* {@link BeforeTransaction &#064;BeforeTransaction} and
* {@link AfterTransaction &#064;AfterTransaction} methods can fail a test in a
* JUnit 4.4 environment, as requested in <a
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-3960"
* target="_blank">SPR-3960</a>.
* </p>
* <p>
* Indirectly, this class also verifies that all {@link TestExecutionListener}
* lifecycle callbacks are called.
* </p>
* <p>
* As of Spring 3.0, this class also tests support for the new
* {@link TestExecutionListener#beforeTestClass(TestContext) beforeTestClass()}
* and {@link TestExecutionListener#afterTestClass(TestContext)
* afterTestClass()} lifecycle callback methods.
* </p>
*
* @author Sam Brannen
* @since 2.5
*/
@RunWith(Parameterized.class)
public class FailingBeforeAndAfterMethodsTests {
protected final Class<?> clazz;
public FailingBeforeAndAfterMethodsTests(final Class<?> clazz) {
this.clazz = clazz;
}
@Parameters
public static Collection<Object[]> testData() {
return Arrays.asList(new Object[][] {//
//
{ AlwaysFailingBeforeTestClassTestCase.class },//
{ AlwaysFailingAfterTestClassTestCase.class },//
{ AlwaysFailingPrepareTestInstanceTestCase.class },//
{ AlwaysFailingBeforeTestMethodTestCase.class },//
{ AlwaysFailingAfterTestMethodTestCase.class },//
{ FailingBeforeTransactionTestCase.class },//
{ FailingAfterTransactionTestCase.class } //
});
}
@Test
public void runTestAndAssertCounters() throws Exception {
final TrackingRunListener listener = new TrackingRunListener();
final RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
new SpringJUnit4ClassRunner(this.clazz).run(notifier);
assertEquals("Verifying number of failures for test class [" + this.clazz + "].", 1,
listener.getTestFailureCount());
}
// -------------------------------------------------------------------
static class AlwaysFailingBeforeTestClassTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) {
fail("always failing beforeTestClass()");
}
}
static class AlwaysFailingAfterTestClassTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestClass(TestContext testContext) {
fail("always failing afterTestClass()");
}
}
static class AlwaysFailingPrepareTestInstanceTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
fail("always failing prepareTestInstance()");
}
}
static class AlwaysFailingBeforeTestMethodTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) {
fail("always failing beforeTestMethod()");
}
}
static class AlwaysFailingAfterTestMethodTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) {
fail("always failing afterTestMethod()");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public static abstract class BaseTestCase {
@Test
public void testNothing() {
}
}
@org.junit.Ignore
@TestExecutionListeners(AlwaysFailingBeforeTestClassTestExecutionListener.class)
public static class AlwaysFailingBeforeTestClassTestCase extends BaseTestCase {
}
@org.junit.Ignore
@TestExecutionListeners(AlwaysFailingAfterTestClassTestExecutionListener.class)
public static class AlwaysFailingAfterTestClassTestCase extends BaseTestCase {
}
@org.junit.Ignore
@TestExecutionListeners(AlwaysFailingPrepareTestInstanceTestExecutionListener.class)
public static class AlwaysFailingPrepareTestInstanceTestCase extends BaseTestCase {
}
@org.junit.Ignore
@TestExecutionListeners(AlwaysFailingBeforeTestMethodTestExecutionListener.class)
public static class AlwaysFailingBeforeTestMethodTestCase extends BaseTestCase {
}
@org.junit.Ignore
@TestExecutionListeners(AlwaysFailingAfterTestMethodTestExecutionListener.class)
public static class AlwaysFailingAfterTestMethodTestCase extends BaseTestCase {
}
@org.junit.Ignore
@ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml")
public static class FailingBeforeTransactionTestCase extends AbstractTransactionalJUnit4SpringContextTests {
@Test
public void testNothing() {
}
@BeforeTransaction
public void beforeTransaction() {
fail("always failing beforeTransaction()");
}
}
@org.junit.Ignore
@ContextConfiguration("FailingBeforeAndAfterMethodsTests-context.xml")
public static class FailingAfterTransactionTestCase extends AbstractTransactionalJUnit4SpringContextTests {
@Test
public void testNothing() {
}
@AfterTransaction
public void afterTransaction() {
fail("always failing afterTransaction()");
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import org.junit.BeforeClass;
import org.springframework.test.annotation.ProfileValueSource;
import org.springframework.test.annotation.ProfileValueSourceConfiguration;
/**
* <p>
* Verifies proper handling of JUnit's {@link org.junit.Ignore &#064;Ignore} and
* Spring's {@link org.springframework.test.annotation.IfProfileValue
* &#064;IfProfileValue} and {@link ProfileValueSourceConfiguration
* &#064;ProfileValueSourceConfiguration} (with an
* <em>explicit, custom defined {@link ProfileValueSource}</em>) annotations in
* conjunction with the {@link SpringJUnit4ClassRunner}.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see EnabledAndIgnoredSpringRunnerTests
*/
@ProfileValueSourceConfiguration(HardCodedProfileValueSourceSpringRunnerTests.HardCodedProfileValueSource.class)
public class HardCodedProfileValueSourceSpringRunnerTests extends EnabledAndIgnoredSpringRunnerTests {
@BeforeClass
public static void setProfileValue() {
numTestsExecuted = 0;
// Set the system property to something other than VALUE as a sanity
// check.
System.setProperty(NAME, "999999999999");
}
public static class HardCodedProfileValueSource implements ProfileValueSource {
public String get(final String key) {
return (key.equals(NAME) ? VALUE : null);
}
}
}

View File

@@ -0,0 +1,35 @@
/*
* 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.test.context.junit4;
import java.lang.annotation.Inherited;
import org.springframework.test.context.ContextConfiguration;
/**
* Extension of {@link SpringJUnit4ClassRunnerAppCtxTests} which verifies that
* the configuration of an application context and dependency injection of a
* test instance function as expected within a class hierarchy, since
* {@link ContextConfiguration configuration} is {@link Inherited inherited}.
*
* @author Sam Brannen
* @since 2.5
* @see SpringJUnit4ClassRunnerAppCtxTests
*/
public class InheritedConfigSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.MethodLevelTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,118 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* JUnit 4 based integration test which verifies support of Spring's
* {@link Transactional &#64;Transactional}, {@link TestExecutionListeners
* &#64;TestExecutionListeners}, and {@link ContextConfiguration
* &#64;ContextConfiguration} annotations in conjunction with the
* {@link SpringJUnit4ClassRunner} and the following
* {@link TestExecutionListener TestExecutionListeners}:
* </p>
* <ul>
* <li>{@link DependencyInjectionTestExecutionListener}</li>
* <li>{@link DirtiesContextTestExecutionListener}</li>
* <li>{@link TransactionalTestExecutionListener}</li>
* </ul>
* <p>
* This class specifically tests usage of <code>&#064;Transactional</code>
* defined at the <strong>method level</strong>. In contrast to
* {@link ClassLevelTransactionalSpringRunnerTests}, this class omits usage of
* <code>&#064;NotTransactional</code>.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see ClassLevelTransactionalSpringRunnerTests
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
public class MethodLevelTransactionalSpringRunnerTests extends AbstractTransactionalSpringRunnerTests {
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", 4,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void verifyInitialTestData() {
clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@Transactional("transactionManager2")
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Deleting bob", 1, deletePerson(simpleJdbcTemplate, BOB));
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
public void modifyTestDataWithoutTransaction() {
assertInTransaction(false);
assertEquals("Adding luke", 1, addPerson(simpleJdbcTemplate, LUKE));
assertEquals("Adding leia", 1, addPerson(simpleJdbcTemplate, LEIA));
assertEquals("Adding yoda", 1, addPerson(simpleJdbcTemplate, YODA));
assertEquals("Verifying the number of rows in the person table without a transaction.", 4,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource2(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="employee" class="org.springframework.beans.Employee">
<property name="name" value="John Smith" />
<property name="age" value="42" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
</beans>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="pet" class="org.springframework.beans.Pet">
<constructor-arg value="Fido" />
</bean>
</beans>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="foo" class="java.lang.String">
<constructor-arg value="Foo" />
</bean>
<bean id="bar" class="java.lang.String">
<constructor-arg value="Bar" />
</bean>
</beans>

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.ResourceUtils;
/**
* Extension of {@link SpringJUnit4ClassRunnerAppCtxTests}, which verifies that
* we can specify multiple resource locations for our application context, each
* configured differently.
* <p>
* As of Spring 3.0,
* <code>MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests</code> is also used
* to verify support for the new <code>value</code> attribute alias for
* <code>&#064;ContextConfiguration</code>'s <code>locations</code> attribute.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see SpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( { MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.CLASSPATH_RESOURCE_PATH,
MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.LOCAL_RESOURCE_PATH,
MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.ABSOLUTE_RESOURCE_PATH })
public class MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
public static final String CLASSPATH_RESOURCE_PATH = ResourceUtils.CLASSPATH_URL_PREFIX
+ "/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml";
public static final String LOCAL_RESOURCE_PATH = "MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml";
public static final String ABSOLUTE_RESOURCE_PATH = "/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context3.xml";
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="employee1" class="org.springframework.beans.Employee">
<property name="name" value="John Smith" />
<property name="age" value="42" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
<bean id="employee2" class="org.springframework.beans.Employee">
<property name="name" value="Jane Smith" />
<property name="age" value="38" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
<bean id="pet" class="org.springframework.beans.Pet">
<constructor-arg value="Fido" />
</bean>
</beans>

View File

@@ -0,0 +1,114 @@
/*
* 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.beans.Employee;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
/**
* Simple JUnit 4 based integration test which demonstrates how to use JUnit's
* {@link Parameterized} Runner in conjunction with
* {@link ContextConfiguration @ContextConfiguration}, the
* {@link DependencyInjectionTestExecutionListener}, and a
* {@link TestContextManager} to provide dependency injection to a
* <em>parameterized test instance</em>.
*
* @author Sam Brannen
* @since 2.5
*/
@RunWith(Parameterized.class)
@ContextConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
public class ParameterizedDependencyInjectionTests {
private static final List<Employee> employees = new ArrayList<Employee>();
@Autowired
private ApplicationContext applicationContext;
@Autowired
private Pet pet;
private final String employeeBeanName;
private final String employeeName;
private final TestContextManager testContextManager;
public ParameterizedDependencyInjectionTests(final String employeeBeanName, final String employeeName)
throws Exception {
this.testContextManager = new TestContextManager(getClass());
this.employeeBeanName = employeeBeanName;
this.employeeName = employeeName;
}
@Parameters
public static Collection<String[]> employeeData() {
return Arrays.asList(new String[][] { { "employee1", "John Smith" }, { "employee2", "Jane Smith" } });
}
@BeforeClass
public static void clearEmployees() {
employees.clear();
}
@Before
public void injectDependencies() throws Throwable {
this.testContextManager.prepareTestInstance(this);
}
@Test
public final void verifyPetAndEmployee() {
// Verifying dependency injection:
assertNotNull("The pet field should have been autowired.", this.pet);
// Verifying 'parameterized' support:
final Employee employee = (Employee) this.applicationContext.getBean(this.employeeBeanName);
employees.add(employee);
assertEquals("Verifying the name of the employee configured as bean [" + this.employeeBeanName + "].",
this.employeeName, employee.getName());
}
@AfterClass
public static void verifyNumParameterizedRuns() {
assertEquals("Verifying the number of times the parameterized test method was executed.",
employeeData().size(), employees.size());
}
}

View File

@@ -0,0 +1,5 @@
cat.(class)=org.springframework.beans.Pet
cat.$0=Garfield
testString.(class)=java.lang.String
testString.$0=Test String

View File

@@ -0,0 +1,78 @@
/*
* 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.GenericPropertiesContextLoader;
/**
* <p>
* JUnit 4 based test class, which verifies the expected functionality of
* {@link SpringJUnit4ClassRunner} in conjunction with support for application
* contexts loaded from Java {@link Properties} files. Specifically, the
* {@link ContextConfiguration#loader() loaderClass} and
* {@link ContextConfiguration#resourceSuffix() resourceSuffix} attributes of
* &#064;ContextConfiguration are tested.
* </p>
* <p>
* Since no {@link ContextConfiguration#locations() locations} are explicitly
* defined, the {@link ContextConfiguration#resourceSuffix() resourceSuffix} is
* set to &quot;-context.properties&quot;, and
* {@link ContextConfiguration#generateDefaultLocations() generateDefaultLocations}
* is left set to its default value of <code>true</code>, this test class's
* dependencies will be injected via
* {@link Autowired annotation-based autowiring} from beans defined in the
* {@link ApplicationContext} loaded from the default classpath resource: &quot;<code>/org/springframework/test/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties</code>&quot;.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see GenericPropertiesContextLoader
* @see SpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = GenericPropertiesContextLoader.class)
public class PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests {
@Autowired
private Pet cat;
@Autowired
private String testString;
@Test
public void verifyAnnotationAutowiredFields() {
assertNotNull("The cat field should have been autowired.", this.cat);
assertEquals("Garfield", this.cat.getName());
assertNotNull("The testString field should have been autowired.", this.testString);
assertEquals("Test String", this.testString);
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
/**
* Extension of {@link SpringJUnit4ClassRunnerAppCtxTests}, which verifies that
* we can specify an explicit, <em>relative path</em> location for our
* application context.
*
* @author Sam Brannen
* @since 2.5
* @see SpringJUnit4ClassRunnerAppCtxTests
* @see AbsolutePathSpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "SpringJUnit4ClassRunnerAppCtxTests-context.xml" })
public class RelativePathSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies proper handling of the following in conjunction with the
* {@link SpringJUnit4ClassRunner}:
* <ul>
* <li>Spring's {@link Repeat &#064;Repeat}</li>
* <li>Spring's {@link Timed &#064;Timed}</li>
* </ul>
*
* @author Sam Brannen
* @since 3.0
*/
@RunWith(Parameterized.class)
public class RepeatedSpringRunnerTests {
private static final AtomicInteger invocationCount = new AtomicInteger();
private final Class<? extends AbstractRepeatedTestCase> testClass;
private final int expectedFailureCount;
private final int expectedTestStartedCount;
private final int expectedTestFinishedCount;
private final int expectedInvocationCount;
public RepeatedSpringRunnerTests(Class<? extends AbstractRepeatedTestCase> testClass, int expectedFailureCount,
int expectedTestStartedCount, int expectedTestFinishedCount, int expectedInvocationCount) {
this.testClass = testClass;
this.expectedFailureCount = expectedFailureCount;
this.expectedTestStartedCount = expectedTestStartedCount;
this.expectedTestFinishedCount = expectedTestFinishedCount;
this.expectedInvocationCount = expectedInvocationCount;
}
@Parameters
public static Collection<Object[]> repetitionData() {
return Arrays.asList(new Object[][] {//
//
{ NonAnnotatedRepeatedTestCase.class, 0, 1, 1, 1 },//
{ DefaultRepeatValueRepeatedTestCase.class, 0, 1, 1, 1 },//
{ NegativeRepeatValueRepeatedTestCase.class, 0, 1, 1, 1 },//
{ RepeatedFiveTimesRepeatedTestCase.class, 0, 1, 1, 5 },//
{ TimedRepeatedTestCase.class, 3, 4, 4, (5 + 1 + 4 + 10) } //
});
}
@Test
public void assertRepetitions() throws Exception {
TrackingRunListener listener = new TrackingRunListener();
RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
invocationCount.set(0);
new SpringJUnit4ClassRunner(this.testClass).run(notifier);
assertEquals("Verifying number of failures for test class [" + this.testClass + "].",
this.expectedFailureCount, listener.getTestFailureCount());
assertEquals("Verifying number of tests started for test class [" + this.testClass + "].",
this.expectedTestStartedCount, listener.getTestStartedCount());
assertEquals("Verifying number of tests finished for test class [" + this.testClass + "].",
this.expectedTestFinishedCount, listener.getTestFinishedCount());
assertEquals("Verifying number of invocations for test class [" + this.testClass + "].",
this.expectedInvocationCount, invocationCount.get());
}
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {})
public abstract static class AbstractRepeatedTestCase {
protected void incrementInvocationCount() throws IOException {
invocationCount.incrementAndGet();
}
}
public static final class NonAnnotatedRepeatedTestCase extends AbstractRepeatedTestCase {
@Test
@Timed(millis = 10000)
public void nonAnnotated() throws Exception {
incrementInvocationCount();
}
}
public static final class DefaultRepeatValueRepeatedTestCase extends AbstractRepeatedTestCase {
@Test
@Repeat
@Timed(millis = 10000)
public void defaultRepeatValue() throws Exception {
incrementInvocationCount();
}
}
public static final class NegativeRepeatValueRepeatedTestCase extends AbstractRepeatedTestCase {
@Test
@Repeat(-5)
@Timed(millis = 10000)
public void negativeRepeatValue() throws Exception {
incrementInvocationCount();
}
}
public static final class RepeatedFiveTimesRepeatedTestCase extends AbstractRepeatedTestCase {
@Test
@Repeat(5)
public void repeatedFiveTimes() throws Exception {
incrementInvocationCount();
}
}
/**
* Unit tests for claims raised in <a
* href="http://jira.springframework.org/browse/SPR-6011"
* target="_blank">SPR-6011</a>.
*/
@org.junit.Ignore // causing timeouts on cbeams' MBP
public static final class TimedRepeatedTestCase extends AbstractRepeatedTestCase {
@Test
@Timed(millis = 10000)
@Repeat(5)
public void repeatedFiveTimesButDoesNotExceedTimeout() throws Exception {
incrementInvocationCount();
}
@Test
@Timed(millis = 100)
@Repeat(1)
public void singleRepetitionExceedsTimeout() throws Exception {
incrementInvocationCount();
Thread.sleep(250);
}
@Test
@Timed(millis = 200)
@Repeat(4)
public void firstRepetitionOfManyExceedsTimeout() throws Exception {
incrementInvocationCount();
Thread.sleep(250);
}
@Test
@Timed(millis = 1000)
@Repeat(10)
public void collectiveRepetitionsExceedTimeout() throws Exception {
incrementInvocationCount();
Thread.sleep(150);
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:transactional_tests" p:username="sa" p:password="" />
<bean id="txMgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:data-source-ref="dataSource" />
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.RollbackOverrideDefaultRollbackFalseTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
/**
* Extension of {@link DefaultRollbackFalseTransactionalSpringRunnerTests} which
* tests method-level <em>rollback override</em> behavior via the
* {@link Rollback @Rollback} annotation.
*
* @author Sam Brannen
* @since 2.5
* @see Rollback
*/
@SuppressWarnings("deprecation")
@ContextConfiguration
public class RollbackOverrideDefaultRollbackFalseTransactionalSpringRunnerTests extends
DefaultRollbackFalseTransactionalSpringRunnerTests {
protected static int originalNumRows;
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", originalNumRows,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
@Override
public void verifyInitialTestData() {
originalNumRows = clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@Rollback(true)
@Override
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Deleting bob", 1, deletePerson(simpleJdbcTemplate, BOB));
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 2,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="databaseSetup"
class="org.springframework.test.context.junit4.RollbackOverrideDefaultRollbackTrueTransactionalSpringRunnerTests$DatabaseSetup" />
</beans>

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* Extension of {@link DefaultRollbackTrueTransactionalSpringRunnerTests} which
* tests method-level <em>rollback override</em> behavior via the
* {@link Rollback @Rollback} annotation.
*
* @author Sam Brannen
* @since 2.5
* @see Rollback
*/
@SuppressWarnings("deprecation")
@ContextConfiguration
public class RollbackOverrideDefaultRollbackTrueTransactionalSpringRunnerTests extends
DefaultRollbackTrueTransactionalSpringRunnerTests {
protected static SimpleJdbcTemplate simpleJdbcTemplate;
@AfterClass
public static void verifyFinalTestData() {
assertEquals("Verifying the final number of rows in the person table after all tests.", 3,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Before
public void verifyInitialTestData() {
clearPersonTable(simpleJdbcTemplate);
assertEquals("Adding bob", 1, addPerson(simpleJdbcTemplate, BOB));
assertEquals("Verifying the initial number of rows in the person table.", 1,
countRowsInPersonTable(simpleJdbcTemplate));
}
@Test
@Transactional
@Rollback(false)
public void modifyTestDataWithinTransaction() {
assertInTransaction(true);
assertEquals("Adding jane", 1, addPerson(simpleJdbcTemplate, JANE));
assertEquals("Adding sue", 1, addPerson(simpleJdbcTemplate, SUE));
assertEquals("Verifying the number of rows in the person table within a transaction.", 3,
countRowsInPersonTable(simpleJdbcTemplate));
}
public static class DatabaseSetup {
@Resource
public void setDataSource(DataSource dataSource) {
simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
createPersonTable(simpleJdbcTemplate);
}
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies support for JUnit 4.7 {@link Rule Rules} in conjunction with the
* {@link SpringJUnit4ClassRunner}. The body of this test class is taken from
* the JUnit 4.7 release notes.
*
* @author JUnit 4.7 Team
* @author Sam Brannen
* @since 3.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {})
public class SpringJUnit47ClassRunnerRuleTests {
@Rule
public TestName name = new TestName();
@Test
public void testA() {
assertEquals("testA", name.getMethodName());
}
@Test
public void testB() {
assertEquals("testB", name.getMethodName());
}
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="employee" class="org.springframework.beans.Employee">
<property name="name" value="John Smith" />
<property name="age" value="42" />
<property name="company" value="Acme Widgets, Inc." />
</bean>
<bean id="pet" class="org.springframework.beans.Pet">
<constructor-arg value="Fido" />
</bean>
<bean id="foo" class="java.lang.String">
<constructor-arg value="Foo" />
</bean>
<bean id="bar" class="java.lang.String">
<constructor-arg value="Bar" />
</bean>
<bean id="quux" class="java.lang.String">
<constructor-arg value="Quux" />
</bean>
</beans>

View File

@@ -0,0 +1,238 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.Employee;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.GenericXmlContextLoader;
/**
* <p>
* SpringJUnit4ClassRunnerAppCtxTests serves as a <em>proof of concept</em>
* JUnit 4 based test class, which verifies the expected functionality of
* {@link SpringJUnit4ClassRunner} in conjunction with the following:
* </p>
* <ul>
* <li>{@link ContextConfiguration @ContextConfiguration}</li>
* <li>{@link Autowired @Autowired}</li>
* <li>{@link Qualifier @Qualifier}</li>
* <li>{@link Resource @Resource}</li>
* <li>{@link Value @Value}</li>
* <li>{@link Inject @Inject}</li>
* <li>{@link Named @Named}</li>
* <li>{@link ApplicationContextAware}</li>
* <li>{@link BeanNameAware}</li>
* <li>{@link InitializingBean}</li>
* </ul>
* <p>
* Since no application context resource
* {@link ContextConfiguration#locations() locations} are explicitly declared
* and since the {@link ContextConfiguration#loader() ContextLoader} is left set
* to the default value of {@link GenericXmlContextLoader}, this test class's
* dependencies will be injected via {@link Autowired @Autowired},
* {@link Inject @Inject}, and {@link Resource @Resource} from beans defined in
* the {@link ApplicationContext} loaded from the default classpath resource:
*
* <code>&quot;/org/springframework/test/context/junit/SpringJUnit4ClassRunnerAppCtxTests-context.xml&quot;</code>
* .
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see AbsolutePathSpringJUnit4ClassRunnerAppCtxTests
* @see RelativePathSpringJUnit4ClassRunnerAppCtxTests
* @see InheritedConfigSpringJUnit4ClassRunnerAppCtxTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class })
public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAware, BeanNameAware, InitializingBean {
/**
* Default resource path for the application context configuration for
* {@link SpringJUnit4ClassRunnerAppCtxTests}:
*
* <code>&quot;/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml&quot;</code>
*/
public static final String DEFAULT_CONTEXT_RESOURCE_PATH = "/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml";
private ApplicationContext applicationContext;
private boolean beanInitialized = false;
private String beanName = "replace me with [" + getClass().getName() + "]";
private Employee employee;
@Autowired
private Pet autowiredPet;
@Inject
private Pet injectedPet;
@Autowired(required = false)
protected Long nonrequiredLong;
@Resource
protected String foo;
protected String bar;
@Value("enigma")
private String literalFieldValue;
@Value("#{2 == (1+1)}")
private Boolean spelFieldValue;
private String literalParameterValue;
private Boolean spelParameterValue;
@Autowired
@Qualifier("quux")
protected String quux;
@Inject
@Named("quux")
protected String namedQuux;
// ------------------------------------------------------------------------|
public final void afterPropertiesSet() throws Exception {
this.beanInitialized = true;
}
public final void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public final void setBeanName(final String beanName) {
this.beanName = beanName;
}
@Autowired
protected final void setEmployee(final Employee employee) {
this.employee = employee;
}
@Resource
protected final void setBar(final String bar) {
this.bar = bar;
}
@Autowired
public void setLiteralParameterValue(@Value("enigma") String literalParameterValue) {
this.literalParameterValue = literalParameterValue;
}
@Autowired
public void setSpelParameterValue(@Value("#{2 == (1+1)}") Boolean spelParameterValue) {
this.spelParameterValue = spelParameterValue;
}
// ------------------------------------------------------------------------|
@Test
public final void verifyApplicationContextSet() {
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.",
this.applicationContext);
}
@Test
public final void verifyBeanInitialized() {
assertTrue("This test bean should have been initialized due to InitializingBean semantics.",
this.beanInitialized);
}
@Test
public final void verifyBeanNameSet() {
assertEquals("The bean name of this test instance should have been set due to BeanNameAware semantics.",
getClass().getName(), this.beanName);
}
@Test
public final void verifyAnnotationAutowiredAndInjectedFields() {
assertNull("The nonrequiredLong field should NOT have been autowired.", this.nonrequiredLong);
assertEquals("The quux field should have been autowired via @Autowired and @Qualifier.", "Quux", this.quux);
assertEquals("The namedFoo field should have been injected via @Inject and @Named.", "Quux", this.namedQuux);
assertSame("@Autowired/@Qualifier and @Inject/@Named quux should be the same object.", this.quux,
this.namedQuux);
assertNotNull("The pet field should have been autowired.", this.autowiredPet);
assertNotNull("The pet field should have been injected.", this.injectedPet);
assertEquals("Fido", this.autowiredPet.getName());
assertEquals("Fido", this.injectedPet.getName());
assertSame("@Autowired and @Inject pet should be the same object.", this.autowiredPet, this.injectedPet);
}
@Test
public final void verifyAnnotationAutowiredMethods() {
assertNotNull("The employee setter method should have been autowired.", this.employee);
assertEquals("John Smith", this.employee.getName());
}
@Test
public final void verifyAutowiredAtValueFields() {
assertNotNull("Literal @Value field should have been autowired", this.literalFieldValue);
assertNotNull("SpEL @Value field should have been autowired.", this.spelFieldValue);
assertEquals("enigma", this.literalFieldValue);
assertEquals(Boolean.TRUE, this.spelFieldValue);
}
@Test
public final void verifyAutowiredAtValueMethods() {
assertNotNull("Literal @Value method parameter should have been autowired.", this.literalParameterValue);
assertNotNull("SpEL @Value method parameter should have been autowired.", this.spelParameterValue);
assertEquals("enigma", this.literalParameterValue);
assertEquals(Boolean.TRUE, this.spelParameterValue);
}
@Test
public final void verifyResourceAnnotationInjectedFields() {
assertEquals("The foo field should have been injected via @Resource.", "Foo", this.foo);
}
@Test
public final void verifyResourceAnnotationInjectedMethods() {
assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar);
}
}

View File

@@ -0,0 +1,48 @@
/*
* 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.test.context.junit4;
import org.junit.Test;
import org.springframework.test.context.TestContextManager;
/**
* @author Rick Evans
* @author Sam Brannen
* @since 2.5
*/
public class SpringJUnit4ClassRunnerTests {
@Test(expected = Exception.class)
public void checkThatExceptionsAreNotSilentlySwallowed() throws Exception {
SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()) {
@Override
protected TestContextManager createTestContextManager(Class<?> clazz) {
return new TestContextManager(clazz) {
@Override
public void prepareTestInstance(Object testInstance) {
throw new RuntimeException("This RuntimeException should be caught and wrapped in an Exception.");
}
};
}
};
runner.createTest();
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2002-2011 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.test.context.ClassLevelDirtiesContextTests;
import org.springframework.test.context.SpringRunnerContextCacheTests;
import org.springframework.test.context.junit4.annotation.AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests;
import org.springframework.test.context.junit4.annotation.BeanOverridingDefaultConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.BeanOverridingExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.DefaultConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderDefaultConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderDefaultConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderExplicitConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.DefaultLoaderExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.annotation.ExplicitConfigClassesBaseTests;
import org.springframework.test.context.junit4.annotation.ExplicitConfigClassesInheritedTests;
import org.springframework.test.context.junit4.orm.HibernateSessionFlushingTests;
import org.springframework.test.context.junit4.profile.annotation.DefaultProfileAnnotationConfigTests;
import org.springframework.test.context.junit4.profile.annotation.DevProfileAnnotationConfigTests;
import org.springframework.test.context.junit4.profile.xml.DefaultProfileXmlConfigTests;
import org.springframework.test.context.junit4.profile.xml.DevProfileXmlConfigTests;
/**
* JUnit test suite for tests involving {@link SpringJUnit4ClassRunner} and the
* <em>Spring TestContext Framework</em>.
*
* <p>This test suite serves a dual purpose of verifying that tests run with
* {@link SpringJUnit4ClassRunner} can be used in conjunction with JUnit's
* {@link Suite} runner.
*
* <p>Note that tests included in this suite will be executed at least twice if
* run from an automated build process, test runner, etc. that is configured to
* run tests based on a &quot;*Tests.class&quot; pattern match.
*
* @author Sam Brannen
* @since 2.5
*/
@RunWith(Suite.class)
// Note: the following 'multi-line' layout is for enhanced code readability.
@SuiteClasses({//
StandardJUnit4FeaturesTests.class,//
StandardJUnit4FeaturesSpringRunnerTests.class,//
SpringJUnit47ClassRunnerRuleTests.class,//
AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.class,//
DefaultConfigClassesBaseTests.class,//
DefaultConfigClassesInheritedTests.class,//
BeanOverridingDefaultConfigClassesInheritedTests.class,//
ExplicitConfigClassesBaseTests.class,//
ExplicitConfigClassesInheritedTests.class,//
BeanOverridingExplicitConfigClassesInheritedTests.class,//
DefaultLoaderDefaultConfigClassesBaseTests.class,//
DefaultLoaderDefaultConfigClassesInheritedTests.class,//
DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.class,//
DefaultLoaderExplicitConfigClassesBaseTests.class,//
DefaultLoaderExplicitConfigClassesInheritedTests.class,//
DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.class,//
DefaultProfileAnnotationConfigTests.class,//
DevProfileAnnotationConfigTests.class,//
DefaultProfileXmlConfigTests.class,//
DevProfileXmlConfigTests.class,//
ExpectedExceptionSpringRunnerTests.class,//
TimedSpringRunnerTests.class,//
RepeatedSpringRunnerTests.class,//
EnabledAndIgnoredSpringRunnerTests.class,//
HardCodedProfileValueSourceSpringRunnerTests.class,//
SpringJUnit4ClassRunnerAppCtxTests.class,//
ClassPathResourceSpringJUnit4ClassRunnerAppCtxTests.class,//
AbsolutePathSpringJUnit4ClassRunnerAppCtxTests.class,//
RelativePathSpringJUnit4ClassRunnerAppCtxTests.class,//
MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests.class,//
InheritedConfigSpringJUnit4ClassRunnerAppCtxTests.class,//
PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.class,//
CustomDefaultContextLoaderClassSpringRunnerTests.class,//
SpringRunnerContextCacheTests.class,//
ClassLevelDirtiesContextTests.class,//
ParameterizedDependencyInjectionTests.class,//
ClassLevelTransactionalSpringRunnerTests.class,//
MethodLevelTransactionalSpringRunnerTests.class,//
DefaultRollbackTrueTransactionalSpringRunnerTests.class,//
DefaultRollbackFalseTransactionalSpringRunnerTests.class,//
RollbackOverrideDefaultRollbackTrueTransactionalSpringRunnerTests.class,//
RollbackOverrideDefaultRollbackFalseTransactionalSpringRunnerTests.class,//
BeforeAndAfterTransactionAnnotationTests.class,//
TimedTransactionalSpringRunnerTests.class,//
HibernateSessionFlushingTests.class //
})
public class SpringJUnit4SuiteTests {
/* this test case consists entirely of tests loaded as a suite. */
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
/**
* <p>
* Simple unit test to verify that {@link SpringJUnit4ClassRunner} does not
* hinder correct functionality of standard JUnit 4.4+ testing features.
* </p>
* <p>
* Note that {@link TestExecutionListeners @TestExecutionListeners} is
* explicitly configured with an empty list, thus disabling all default
* listeners.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see StandardJUnit4FeaturesTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public class StandardJUnit4FeaturesSpringRunnerTests extends StandardJUnit4FeaturesTests {
/* All tests are in the parent class... */
}

View File

@@ -0,0 +1,108 @@
/*
* 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
* Simple unit test to verify the expected functionality of standard JUnit 4.4+
* testing features.
* <p>
* Currently testing: {@link Test @Test} (including expected exceptions and
* timeouts), {@link BeforeClass @BeforeClass}, {@link Before @Before}, and
* <em>assumptions</em>.
* </p>
* <p>
* Due to the fact that JUnit does not guarantee a particular ordering of test
* method execution, the following are currently not tested:
* {@link org.junit.AfterClass @AfterClass} and {@link org.junit.After @After}.
* </p>
*
* @author Sam Brannen
* @since 2.5
* @see StandardJUnit4FeaturesSpringRunnerTests
*/
public class StandardJUnit4FeaturesTests {
private static int staticBeforeCounter = 0;
@BeforeClass
public static void incrementStaticBeforeCounter() {
StandardJUnit4FeaturesTests.staticBeforeCounter++;
}
private int beforeCounter = 0;
@Test
@Ignore
public void alwaysFailsButShouldBeIgnored() {
fail("The body of an ignored test should never be executed!");
}
@Test
public void alwaysSucceeds() {
assertTrue(true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void expectingAnIndexOutOfBoundsException() {
new ArrayList<Object>().get(1);
}
@Test
public void failedAssumptionShouldPrecludeImminentFailure() {
assumeTrue(false);
fail("A failed assumption should preclude imminent failure!");
}
@Before
public void incrementBeforeCounter() {
this.beforeCounter++;
}
@Test(timeout = 10000)
public void noOpShouldNotTimeOut() {
/* no-op */
}
@Test
public void verifyBeforeAnnotation() {
assertEquals(1, this.beforeCounter);
}
@Test
public void verifyBeforeClassAnnotation() {
// Instead of testing for equality to 1, we just assert that the value
// was incremented at least once, since this test class may serve as a
// parent class to other tests in a suite, etc.
assertTrue(StandardJUnit4FeaturesTests.staticBeforeCounter > 0);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.TestExecutionListeners;
/**
* Verifies proper handling of the following in conjunction with the
* {@link SpringJUnit4ClassRunner}:
* <ul>
* <li>JUnit's {@link Test#timeout() @Test(timeout=...)}</li>
* <li>Spring's {@link Timed @Timed}</li>
* </ul>
*
* @author Sam Brannen
* @since 3.0
*/
@RunWith(JUnit4.class)
public class TimedSpringRunnerTests {
@Test
public void timedTests() throws Exception {
Class<TimedSpringRunnerTestCase> testClass = TimedSpringRunnerTestCase.class;
TrackingRunListener listener = new TrackingRunListener();
RunNotifier notifier = new RunNotifier();
notifier.addListener(listener);
new SpringJUnit4ClassRunner(testClass).run(notifier);
assertEquals("Verifying number of failures for test class [" + testClass + "].", 3,
listener.getTestFailureCount());
assertEquals("Verifying number of tests started for test class [" + testClass + "].", 5,
listener.getTestStartedCount());
assertEquals("Verifying number of tests finished for test class [" + testClass + "].", 5,
listener.getTestFinishedCount());
}
@org.junit.Ignore // causing timeouts on cbeams' MBP
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {})
public static final class TimedSpringRunnerTestCase {
// Should Pass.
@Test(timeout = 2000)
public void testJUnitTimeoutWithNoOp() {
/* no-op */
}
// Should Pass.
@Test
@Timed(millis = 2000)
public void testSpringTimeoutWithNoOp() {
/* no-op */
}
// Should Fail due to timeout.
@Test(timeout = 200)
public void testJUnitTimeoutWithOneSecondWait() throws Exception {
Thread.sleep(1000);
}
// Should Fail due to timeout.
@Test
@Timed(millis = 200)
public void testSpringTimeoutWithOneSecondWait() throws Exception {
Thread.sleep(1000);
}
// Should Fail due to duplicate configuration.
@Test(timeout = 200)
@Timed(millis = 200)
public void testSpringAndJUnitTimeout() {
/* no-op */
}
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2008 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.test.context.junit4;
import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.annotation.Timed;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* JUnit 4 based integration test which verifies support of Spring's
* {@link Transactional &#64;Transactional} and {@link NotTransactional
* &#64;NotTransactional} annotations in conjunction with {@link Timed
* &#64;Timed} and JUnit 4's {@link Test#timeout() timeout} attribute.
*
* @author Sam Brannen
* @since 2.5
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("transactionalTests-context.xml")
@Transactional
@SuppressWarnings("deprecation")
public class TimedTransactionalSpringRunnerTests {
@Test
@Timed(millis = 10000)
@Repeat(5)
public void transactionalWithSpringTimeout() {
assertInTransaction(true);
}
@Test(timeout = 10000)
@Repeat(5)
public void transactionalWithJUnitTimeout() {
assertInTransaction(true);
}
@Test
@NotTransactional
@Timed(millis = 10000)
@Repeat(5)
public void notTransactionalWithSpringTimeout() {
assertInTransaction(false);
}
@Test(timeout = 10000)
@NotTransactional
@Repeat(5)
public void notTransactionalWithJUnitTimeout() {
assertInTransaction(false);
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright 2002-2009 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.test.context.junit4;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
/**
* Simple {@link RunListener} which tracks how many times certain JUnit callback
* methods were called: only intended for the integration test suite.
*
* @author Sam Brannen
* @since 3.0
*/
public class TrackingRunListener extends RunListener {
private final AtomicInteger testFailureCount = new AtomicInteger();
private final AtomicInteger testStartedCount = new AtomicInteger();
private final AtomicInteger testFinishedCount = new AtomicInteger();
public int getTestFailureCount() {
return this.testFailureCount.get();
}
public int getTestStartedCount() {
return this.testStartedCount.get();
}
public int getTestFinishedCount() {
return this.testFinishedCount.get();
}
@Override
public void testFailure(Failure failure) throws Exception {
this.testFailureCount.incrementAndGet();
}
@Override
public void testStarted(Description description) throws Exception {
this.testStartedCount.incrementAndGet();
}
@Override
public void testFinished(Description description) throws Exception {
this.testFinishedCount.incrementAndGet();
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunnerAppCtxTests;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
* <p>Furthermore, by extending {@link SpringJUnit4ClassRunnerAppCtxTests},
* this class also verifies support for several basic features of the
* Spring TestContext Framework. See JavaDoc in
* <code>SpringJUnit4ClassRunnerAppCtxTests</code> for details.
*
* <p>Configuration will be loaded from {@link PojoAndStringConfig}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration(classes = PojoAndStringConfig.class, inheritLocations = false)
public class AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests extends SpringJUnit4ClassRunnerAppCtxTests {
/* all tests are in the parent class. */
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* JUnit test suite for annotation-driven <em>configuration class</em>
* support in the Spring TestContext Framework.
*
* @author Sam Brannen
* @since 3.1
*/
@RunWith(Suite.class)
// Note: the following 'multi-line' layout is for enhanced code readability.
@SuiteClasses({//
AnnotationConfigSpringJUnit4ClassRunnerAppCtxTests.class,//
DefaultConfigClassesBaseTests.class,//
DefaultConfigClassesInheritedTests.class,//
BeanOverridingDefaultConfigClassesInheritedTests.class,//
ExplicitConfigClassesBaseTests.class,//
ExplicitConfigClassesInheritedTests.class,//
BeanOverridingExplicitConfigClassesInheritedTests.class,//
DefaultLoaderDefaultConfigClassesBaseTests.class,//
DefaultLoaderDefaultConfigClassesInheritedTests.class,//
DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.class,//
DefaultLoaderExplicitConfigClassesBaseTests.class,//
DefaultLoaderExplicitConfigClassesInheritedTests.class,//
DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.class //
})
public class AnnotationConfigTestSuite {
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
* <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
* and {@link BeanOverridingDefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration
public class BeanOverridingDefaultConfigClassesInheritedTests extends DefaultConfigClassesBaseTests {
@Configuration
static class ContextConfiguration {
@Bean
public Employee employee() {
Employee employee = new Employee();
employee.setName("Yoda");
employee.setAge(900);
employee.setCompany("The Force");
return employee;
}
}
@Test
@Override
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee should have been autowired.", this.employee);
assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
* <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
* and {@link BeanOverridingDefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration(classes = BeanOverridingDefaultConfigClassesInheritedTests.ContextConfiguration.class)
public class BeanOverridingExplicitConfigClassesInheritedTests extends ExplicitConfigClassesBaseTests {
@Test
@Override
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee should have been autowired.", this.employee);
assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
* <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
* @see DefaultLoaderDefaultConfigClassesBaseTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DefaultConfigClassesBaseTests {
@Configuration
static class ContextConfiguration {
@Bean
public Employee employee() {
Employee employee = new Employee();
employee.setName("John Smith");
employee.setAge(42);
employee.setCompany("Acme Widgets, Inc.");
return employee;
}
}
@Autowired
protected Employee employee;
@Test
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee field should have been autowired.", this.employee);
assertEquals("John Smith", this.employee.getName());
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework.
*
* <p>Configuration will be loaded from {@link DefaultConfigClassesBaseTests.ContextConfiguration}
* and {@link DefaultConfigClassesInheritedTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration
public class DefaultConfigClassesInheritedTests extends DefaultConfigClassesBaseTests {
@Configuration
static class ContextConfiguration {
@Bean
public Pet pet() {
return new Pet("Fido");
}
}
@Autowired
private Pet pet;
@Test
public void verifyPetSetFromExtendedContextConfig() {
assertNotNull("The pet should have been autowired.", this.pet);
assertEquals("Fido", this.pet.getName());
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework in conjunction with the
* {@link DelegatingSmartContextLoader}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration
public class DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests extends
DefaultLoaderDefaultConfigClassesBaseTests {
@Configuration
static class Config {
@Bean
public Employee employee() {
Employee employee = new Employee();
employee.setName("Yoda");
employee.setAge(900);
employee.setCompany("The Force");
return employee;
}
}
@Test
@Override
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee should have been autowired.", this.employee);
assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework in conjunction with the
* {@link DelegatingSmartContextLoader}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration(classes = DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.Config.class)
public class DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests extends
DefaultLoaderExplicitConfigClassesBaseTests {
@Test
@Override
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee should have been autowired.", this.employee);
assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName());
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework in conjunction with the
* {@link DelegatingSmartContextLoader}.
*
* @author Sam Brannen
* @since 3.1
* @see DefaultConfigClassesBaseTests
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DefaultLoaderDefaultConfigClassesBaseTests {
@Configuration
static class Config {
@Bean
public Employee employee() {
Employee employee = new Employee();
employee.setName("John Smith");
employee.setAge(42);
employee.setCompany("Acme Widgets, Inc.");
return employee;
}
}
@Autowired
protected Employee employee;
@Test
public void verifyEmployeeSetFromBaseContextConfig() {
assertNotNull("The employee field should have been autowired.", this.employee);
assertEquals("John Smith", this.employee.getName());
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2011 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.test.context.junit4.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.beans.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
/**
* Integration tests that verify support for configuration classes in
* the Spring TestContext Framework in conjunction with the
* {@link DelegatingSmartContextLoader}.
*
* @author Sam Brannen
* @since 3.1
*/
@ContextConfiguration
public class DefaultLoaderDefaultConfigClassesInheritedTests extends DefaultLoaderDefaultConfigClassesBaseTests {
@Configuration
static class Config {
@Bean
public Pet pet() {
return new Pet("Fido");
}
}
@Autowired
private Pet pet;
@Test
public void verifyPetSetFromExtendedContextConfig() {
assertNotNull("The pet should have been autowired.", this.pet);
assertEquals("Fido", this.pet.getName());
}
}

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