├── .gitignore ├── etc ├── header.txt └── checkstyle.xml ├── README ├── src ├── test │ ├── resources │ │ ├── META-INF │ │ │ ├── persistence.xml │ │ │ └── beans.xml │ │ ├── fixtures.xml │ │ └── log4j.xml │ └── java │ │ ├── com │ │ └── example │ │ │ ├── dao │ │ │ ├── WidgetDao.java │ │ │ └── jpa │ │ │ │ └── JpaWidgetDao.java │ │ │ ├── ejb3 │ │ │ └── beans │ │ │ │ └── WidgetBean.java │ │ │ └── model │ │ │ └── Widget.java │ │ └── junit │ │ └── rules │ │ ├── AllTests.java │ │ ├── util │ │ └── SimpleReference.java │ │ ├── derby │ │ └── DerbyDataSourceRuleTest.java │ │ ├── jpa │ │ └── hibernate │ │ │ ├── HibernatePersistenceContextTest.java │ │ │ └── DerbyHibernateTestCaseTest.java │ │ ├── jndi │ │ └── StubJndiContextTest.java │ │ ├── cdi │ │ └── WeldTest.java │ │ ├── jetty │ │ └── JettyServerRuleTest.java │ │ ├── httpserver │ │ └── HttpServerRuleTest.java │ │ └── ExpectedExceptionsTest.java └── main │ └── java │ └── junit │ └── rules │ ├── jpa │ ├── PersistenceContext.java │ └── hibernate │ │ ├── DerbyHibernateUtil.java │ │ ├── DerbyHibernateTestCase.java │ │ └── HibernatePersistenceContext.java │ ├── dbunit │ ├── Fixtures.java │ ├── FixturesUtil.java │ ├── DbUnitUtil.java │ └── DbUnitTestFixtures.java │ ├── cdi │ ├── Mock.java │ └── Weld.java │ ├── util │ ├── StringUtils.java │ ├── ReadOnlyIterator.java │ ├── ObjectUtils.java │ └── Reflection.java │ ├── Throws.java │ ├── httpserver │ ├── BaseHttpServerRule.java │ ├── HttpServerRule.java │ └── SimpleHttpHandler.java │ ├── TestFixture.java │ ├── ExpectedExceptions.java │ ├── jetty │ ├── SimpleJettyHandler.java │ └── JettyServerRule.java │ ├── jdbc │ └── support │ │ └── DriverManagerDataSource.java │ ├── derby │ └── DerbyDataSourceRule.java │ └── jndi │ └── StubJndiContext.java ├── LICENSE.txt └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | !.gitignore 3 | target/ 4 | nbactions.xml 5 | nbproject 6 | derby.log 7 | -------------------------------------------------------------------------------- /etc/header.txt: -------------------------------------------------------------------------------- 1 | ^/\*\*$ 2 | ^ \* junit-rules: JUnit Rules Library$ 3 | ^ \*$ 4 | ^ \* Copyright \(c\) 2009-20\d{2} by Alistair A\. Israel\.$ 5 | ^ \* This software is made available under the terms of the MIT License\.$ 6 | ^ \*$ 7 | ^ \* Created [A-Z][a-z]{2} \d{1,2}, \d{4}$ 8 | ^ \*/$ 9 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | junit-rules provides a showcase of JUnit rules 2 | 3 | Further reading: 4 | 5 | * Functional HTTP testing revisited using JUnit 4.7 Interceptors 6 | http://alistairisrael.wordpress.com/2009/09/03/functional-http-testing-revisited-using-junit-interceptors/ 7 | * Kent Beck, Interceptors in JUnit 8 | http://www.threeriversinstitute.org/blog/?p=155 9 | -------------------------------------------------------------------------------- /src/test/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/test/resources/META-INF/beans.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | junit.rules.cdi.Mock 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/test/resources/fixtures.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | id 5 | name 6 | 7 | 1 8 | First widget 9 | 10 | 11 | 2 12 | Second widget 13 | 14 |
15 |
16 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jpa/PersistenceContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 16, 2009 8 | */ 9 | package junit.rules.jpa; 10 | 11 | /** 12 | * @author Alistair A. Israel 13 | */ 14 | public interface PersistenceContext { 15 | 16 | /** 17 | * @param object 18 | * an object to which we will apply EJB 3.0 style @PersistenceContext and @PostConstruct handling 19 | */ 20 | void injectAndPostConstruct(Object object); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/dbunit/Fixtures.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 16, 2009 8 | */ 9 | package junit.rules.dbunit; 10 | 11 | import static java.lang.annotation.ElementType.TYPE; 12 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 13 | 14 | import java.lang.annotation.Retention; 15 | import java.lang.annotation.Target; 16 | 17 | /** 18 | * @author Alistair A. Israel 19 | */ 20 | @Target(TYPE) 21 | @Retention(RUNTIME) 22 | public @interface Fixtures { 23 | 24 | /** 25 | * The fixture names. 26 | */ 27 | String[] value(); 28 | } 29 | -------------------------------------------------------------------------------- /src/test/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/cdi/Mock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Feb 16, 2011 8 | */ 9 | package junit.rules.cdi; 10 | 11 | import static java.lang.annotation.ElementType.FIELD; 12 | import static java.lang.annotation.ElementType.TYPE; 13 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 14 | 15 | import java.lang.annotation.Retention; 16 | import java.lang.annotation.Target; 17 | 18 | import javax.enterprise.inject.Alternative; 19 | import javax.enterprise.inject.Stereotype; 20 | 21 | /** 22 | * 23 | * @author Alistair A. Israel 24 | */ 25 | @Alternative 26 | @Stereotype 27 | @Retention(RUNTIME) 28 | @Target({ TYPE, FIELD }) 29 | public @interface Mock { 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/example/dao/WidgetDao.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 15, 2009 8 | */ 9 | package com.example.dao; 10 | 11 | import java.util.List; 12 | 13 | import com.example.model.Widget; 14 | 15 | /** 16 | * @author Alistair A. Israel 17 | */ 18 | public interface WidgetDao { 19 | 20 | /** 21 | * @return {@link List}<{@link Widget}> 22 | */ 23 | List listAll(); 24 | 25 | /** 26 | * @param id 27 | * the widget id 28 | * @return {@link Widget} 29 | */ 30 | Widget findById(int id); 31 | 32 | /** 33 | * @param name 34 | * the widget name 35 | * @return {@link Widget} 36 | */ 37 | Widget findByName(String name); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/util/StringUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 5, 2011 8 | */ 9 | package junit.rules.util; 10 | 11 | /** 12 | * @author Alistair A. Israel 13 | */ 14 | public final class StringUtils { 15 | 16 | /** 17 | * Utility classes should not have a public or default constructor. 18 | */ 19 | private StringUtils() { 20 | // noop 21 | } 22 | 23 | /** 24 | * Checks if the given string is not {@code null} or empty. 25 | * 26 | * @param s 27 | * the string to check 28 | * @return {@code true} if the String is not {@code null} and has length > 0 29 | */ 30 | public static boolean hasLength(final String s) { 31 | return s != null && s.length() > 0; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/AllTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package junit.rules; 10 | 11 | import junit.rules.httpserver.HttpServerRuleTest; 12 | import junit.rules.jetty.JettyServerRuleTest; 13 | import junit.rules.jpa.hibernate.DerbyHibernateTestCaseTest; 14 | import junit.rules.jpa.hibernate.HibernatePersistenceContextTest; 15 | 16 | import org.junit.runner.RunWith; 17 | import org.junit.runners.Suite; 18 | import org.junit.runners.Suite.SuiteClasses; 19 | 20 | /** 21 | * @author Alistair A. Israel 22 | */ 23 | @RunWith(Suite.class) 24 | @SuiteClasses({ 25 | HttpServerRuleTest.class, 26 | JettyServerRuleTest.class, 27 | DerbyHibernateTestCaseTest.class, 28 | HibernatePersistenceContextTest.class 29 | }) 30 | public class AllTests { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/util/ReadOnlyIterator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 17, 2011 8 | */ 9 | package junit.rules.util; 10 | 11 | import java.util.Iterator; 12 | 13 | /** 14 | * A read-only iterator that throws {@link UnsupportedOperationException} on {@link #remove()}. 15 | * 16 | * @param 17 | * a type 18 | * @author Alistair A. Israel 19 | */ 20 | public abstract class ReadOnlyIterator implements Iterator { 21 | 22 | /** 23 | * Will throw {@link UnsupportedOperationException}. 24 | * 25 | * @see java.util.Iterator#remove() 26 | */ 27 | @Override 28 | public final void remove() { 29 | throw new UnsupportedOperationException("remove() not allowed for " + this.getClass().getCanonicalName() 30 | + " [ReadOnlyIterator]!"); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/Throws.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 5, 2011 8 | */ 9 | package junit.rules; 10 | 11 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 12 | 13 | import java.lang.annotation.ElementType; 14 | import java.lang.annotation.Retention; 15 | import java.lang.annotation.Target; 16 | 17 | /** 18 | * @author Alistair A. Israel 19 | */ 20 | @Target({ ElementType.METHOD }) 21 | @Retention(RUNTIME) 22 | public @interface Throws { 23 | 24 | /** 25 | * The {@link Throwable} to expect 26 | */ 27 | Class value(); 28 | 29 | /** 30 | * The expected message 31 | */ 32 | String message() default DEFAULT; 33 | 34 | /** 35 | * A default value for the exception message, only because Java annotations can't have {@code null} as a value. 36 | */ 37 | String DEFAULT = "\0"; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/util/ObjectUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 5, 2011 8 | */ 9 | package junit.rules.util; 10 | 11 | /** 12 | * @author Alistair A. Israel 13 | */ 14 | public final class ObjectUtils { 15 | 16 | /** 17 | * Utility classes should not have a public or default constructor. 18 | */ 19 | private ObjectUtils() { 20 | // noop 21 | } 22 | 23 | /** 24 | * Null safe equals. 25 | * 26 | * @param 27 | * a type 28 | * @param a 29 | * the first object to test 30 | * @param b 31 | * the second object to test 32 | * @return {@code true}, if 33 | */ 34 | public static boolean nullSafeEquals(final T a, final T b) { 35 | if (a == b) { 36 | return true; 37 | } 38 | if (a == null || b == null) { 39 | return false; 40 | } 41 | return a.equals(b); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2009-2011 Alistair A. Israel 4 | 5 | Permission is hereby granted, free of charge, to any person 6 | obtaining a copy of this software and associated documentation 7 | files (the "Software"), to deal in the Software without 8 | restriction, including without limitation the rights to use, 9 | copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the 11 | Software is furnished to do so, subject to the following 12 | conditions: 13 | 14 | The above copyright notice and this permission notice shall be 15 | included in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 19 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 22 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 23 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | OTHER DEALINGS IN THE SOFTWARE. 25 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/util/SimpleReference.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Apr 26, 2011 8 | */ 9 | package junit.rules.util; 10 | 11 | /** 12 | * Used only to get around the restriction that only final variables can be visible inside anonymous inner classes. 13 | * 14 | * @param 15 | * a type 16 | * @author Alistair A. Israel 17 | */ 18 | public class SimpleReference { 19 | 20 | private T value; 21 | 22 | /** 23 | * @return the object referenced 24 | */ 25 | public final T get() { 26 | return value; 27 | } 28 | 29 | /** 30 | * @param obj 31 | * the new object to reference 32 | */ 33 | public final void set(final T obj) { 34 | this.value = obj; 35 | } 36 | 37 | /** 38 | * @param 39 | * a type 40 | * @param obj 41 | * the object we want to reference 42 | * @return a SimpleReference to the object 43 | */ 44 | public static SimpleReference to(final T obj) { 45 | return new SimpleReference(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/dbunit/FixturesUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package junit.rules.dbunit; 10 | 11 | import java.lang.reflect.AnnotatedElement; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * @author Alistair A. Israel 17 | */ 18 | public final class FixturesUtil { 19 | 20 | /** 21 | * Utility classes should not have a public or default constructor. 22 | */ 23 | private FixturesUtil() { 24 | // noop 25 | } 26 | 27 | /** 28 | * @param elements 29 | * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation 30 | * @return the list of fixture names 31 | */ 32 | public static List getFixtureNames(final AnnotatedElement... elements) { 33 | final List fixtureNames = new ArrayList(); 34 | for (final AnnotatedElement element : elements) { 35 | if (element.isAnnotationPresent(Fixtures.class)) { 36 | for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) { 37 | fixtureNames.add(fixtureName); 38 | } 39 | } 40 | } 41 | return fixtureNames; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/example/ejb3/beans/WidgetBean.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 16, 2009 8 | */ 9 | package com.example.ejb3.beans; 10 | 11 | import java.util.List; 12 | 13 | import javax.annotation.PostConstruct; 14 | import javax.persistence.EntityManager; 15 | import javax.persistence.PersistenceContext; 16 | 17 | import com.example.dao.WidgetDao; 18 | import com.example.dao.jpa.JpaWidgetDao; 19 | import com.example.model.Widget; 20 | 21 | /** 22 | * @author Alistair A. Israel 23 | */ 24 | public class WidgetBean { 25 | 26 | @PersistenceContext 27 | private EntityManager em; 28 | 29 | private WidgetDao widgetDao; 30 | 31 | /** 32 | * We create the {@link JpaWidgetDao} 33 | */ 34 | @PostConstruct 35 | @SuppressWarnings("unused") 36 | private void initialize() { 37 | widgetDao = new JpaWidgetDao(em); 38 | } 39 | 40 | /** 41 | * @return list of all widgets 42 | */ 43 | public final List listAll() { 44 | return widgetDao.listAll(); 45 | } 46 | 47 | /** 48 | * @param id 49 | * the Widget id 50 | * @return the found Widget 51 | */ 52 | public final Widget findById(final int id) { 53 | return widgetDao.findById(id); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/derby/DerbyDataSourceRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 5, 2011 8 | */ 9 | package junit.rules.derby; 10 | 11 | import static org.junit.Assert.assertNotNull; 12 | 13 | import java.sql.Connection; 14 | import java.sql.Date; 15 | import java.sql.ResultSet; 16 | import java.sql.Statement; 17 | 18 | import org.junit.Rule; 19 | import org.junit.Test; 20 | 21 | /** 22 | * JUnit test for {@link DerbyDataSourceRule}. 23 | * 24 | * @author Alistair A. Israel 25 | */ 26 | public final class DerbyDataSourceRuleTest { 27 | 28 | // CHECKSTYLE:OFF 29 | @Rule 30 | public final DerbyDataSourceRule derby = new DerbyDataSourceRule("test"); 31 | // CHECKSTYLE:ON 32 | 33 | /** 34 | * @throws Exception 35 | * should never happen 36 | */ 37 | @Test 38 | public void testDerbyDataSourceRule() throws Exception { 39 | final Connection conn = derby.getConnection(); 40 | assertNotNull(conn); 41 | try { 42 | final Statement ps = conn.createStatement(); 43 | try { 44 | final ResultSet rs = ps.executeQuery("VALUES CURRENT_DATE"); 45 | rs.next(); 46 | final Date today = rs.getDate(1); 47 | assertNotNull(today); 48 | } finally { 49 | ps.close(); 50 | } 51 | } finally { 52 | conn.close(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/httpserver/BaseHttpServerRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Mar 9, 2010 8 | */ 9 | package junit.rules.httpserver; 10 | 11 | import java.io.IOException; 12 | import java.net.HttpURLConnection; 13 | 14 | import junit.rules.TestFixture; 15 | 16 | /** 17 | * @author Alistair A. Israel 18 | */ 19 | public abstract class BaseHttpServerRule extends TestFixture { 20 | 21 | /** 22 | * The default HTTP port to listen to, port 8000 23 | */ 24 | public static final int DEFAULT_HTTP_PORT = 8000; 25 | 26 | /** 27 | * @param path 28 | * the URI path to GET 29 | * @return the HttpURLConnection 30 | * @throws IOException 31 | * on exception 32 | */ 33 | public abstract HttpURLConnection get(final String path) throws IOException; 34 | 35 | /** 36 | * @param path 37 | * the URI path to POST to 38 | * @return the HttpURLConnection 39 | * @throws IOException 40 | * on exception 41 | */ 42 | public abstract HttpURLConnection post(final String path) throws IOException; 43 | 44 | /** 45 | * @param path 46 | * the URI path to PUT to 47 | * @return the HttpURLConnection 48 | * @throws IOException 49 | * on exception 50 | */ 51 | public abstract HttpURLConnection put(final String path) throws IOException; 52 | 53 | /** 54 | * @param path 55 | * the URI path to DELETE 56 | * @return the HttpURLConnection 57 | * @throws IOException 58 | * on exception 59 | */ 60 | public abstract HttpURLConnection delete(final String path) throws IOException; 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/jpa/hibernate/HibernatePersistenceContextTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 15, 2009 8 | */ 9 | package junit.rules.jpa.hibernate; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | 14 | import java.util.List; 15 | 16 | import junit.rules.dbunit.Fixtures; 17 | 18 | import org.junit.Rule; 19 | import org.junit.Test; 20 | 21 | import com.example.ejb3.beans.WidgetBean; 22 | import com.example.model.Widget; 23 | 24 | /** 25 | * @author Alistair A. Israel 26 | * @since 0.3 27 | */ 28 | @Fixtures("fixtures.xml") 29 | public final class HibernatePersistenceContextTest { 30 | 31 | // CHECKSTYLE:OFF 32 | @Rule 33 | public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext(); 34 | // CHECKSTYLE:ON 35 | 36 | private WidgetBean widgetBean = new WidgetBean(); 37 | 38 | /** 39 | * @throws Exception 40 | * on exception 41 | */ 42 | @Test 43 | public void testListAll() throws Exception { 44 | persistenceContext.injectAndPostConstruct(widgetBean); 45 | 46 | final List widgets = widgetBean.listAll(); 47 | assertNotNull(widgets); 48 | assertEquals(2, widgets.size()); 49 | } 50 | 51 | /** 52 | * @throws Exception 53 | * on exception 54 | */ 55 | @Test 56 | public void testFindById() throws Exception { 57 | persistenceContext.injectAndPostConstruct(widgetBean); 58 | 59 | final Widget widget = widgetBean.findById(2); 60 | assertNotNull(widget); 61 | assertEquals(2, widget.getId().intValue()); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package junit.rules.jpa.hibernate; 10 | 11 | import java.sql.DriverManager; 12 | import java.sql.SQLException; 13 | import java.util.Properties; 14 | 15 | import org.hibernate.ejb.Ejb3Configuration; 16 | 17 | /** 18 | * @author Alistair A. Israel 19 | */ 20 | public final class DerbyHibernateUtil { 21 | 22 | /** 23 | * {@value #JDBC_DERBY_URL} 24 | */ 25 | public static final String JDBC_DERBY_URL = "jdbc:derby:test"; 26 | 27 | /** 28 | * 29 | */ 30 | private DerbyHibernateUtil() { 31 | // noop 32 | } 33 | 34 | /** 35 | * @param classes 36 | * the annotated classes 37 | * @return {@link Ejb3Configuration} 38 | */ 39 | public static Ejb3Configuration configureDerbyHibernateJpa(final Class... classes) { 40 | try { 41 | DriverManager.getConnection(JDBC_DERBY_URL + ";create=true"); 42 | } catch (final SQLException e) { 43 | throw new RuntimeException(e.getMessage(), e); 44 | } 45 | 46 | final Properties properties = new Properties(); 47 | properties.put("hibernate.connection.url", JDBC_DERBY_URL); 48 | properties.put("hibernate.connection.pool_size", "5"); 49 | properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); 50 | properties.put("hibernate.hbm2ddl.auto", "create-drop"); 51 | 52 | final Ejb3Configuration cfg = new Ejb3Configuration(); 53 | cfg.configure("test", properties); 54 | for (final Class clazz : classes) { 55 | cfg.addAnnotatedClass(clazz); 56 | } 57 | return cfg; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/example/dao/jpa/JpaWidgetDao.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package com.example.dao.jpa; 10 | 11 | import java.util.List; 12 | 13 | import javax.persistence.EntityManager; 14 | 15 | import com.example.dao.WidgetDao; 16 | import com.example.model.Widget; 17 | 18 | /** 19 | * @author Alistair A. Israel 20 | */ 21 | public class JpaWidgetDao implements WidgetDao { 22 | 23 | private final EntityManager entityManager; 24 | 25 | /** 26 | * @param entityManager 27 | * the {@link EntityManager} 28 | */ 29 | public JpaWidgetDao(final EntityManager entityManager) { 30 | this.entityManager = entityManager; 31 | } 32 | 33 | /** 34 | * {@inheritDoc} 35 | * 36 | * @see com.example.dao.WidgetDao#findById(int) 37 | */ 38 | @Override 39 | public final Widget findById(final int id) { 40 | return entityManager.find(Widget.class, id); 41 | } 42 | 43 | /** 44 | * {@inheritDoc} 45 | * 46 | * @see com.example.dao.WidgetDao#findByName(java.lang.String) 47 | */ 48 | @Override 49 | @SuppressWarnings("unchecked") 50 | public final Widget findByName(final String name) { 51 | final List list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name) 52 | .getResultList(); 53 | if (list.isEmpty()) { 54 | return null; 55 | } 56 | return list.get(0); 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | * 62 | * @see com.example.dao.WidgetDao#listAll() 63 | */ 64 | @Override 65 | @SuppressWarnings("unchecked") 66 | public final List listAll() { 67 | return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList(); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/TestFixture.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 3, 2009 8 | */ 9 | package junit.rules; 10 | 11 | import org.junit.rules.TestRule; 12 | import org.junit.runner.Description; 13 | import org.junit.runners.model.Statement; 14 | 15 | /** 16 | * @author Alistair A. Israel 17 | */ 18 | public class TestFixture implements TestRule { 19 | 20 | /** 21 | * {@inheritDoc} 22 | * 23 | * @see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, org.junit.runners.model.FrameworkMethod, 24 | * java.lang.Object) 25 | */ 26 | @Override 27 | public final Statement apply(final Statement base, final Description description) { 28 | inspect(description); 29 | return new Statement() { 30 | @Override 31 | public void evaluate() throws Throwable { 32 | setUp(); 33 | try { 34 | base.evaluate(); 35 | } finally { 36 | tearDown(); 37 | } 38 | } 39 | }; 40 | } 41 | 42 | /** 43 | * Override to perform any reflection/introspection on the target test instance before setUp() / tearDown(). 44 | * 45 | * @param description the {@link Description} 46 | */ 47 | protected void inspect(final Description description) { 48 | } 49 | 50 | /** 51 | * Override to set up your specific external resource. 52 | * 53 | * @throws Throwable 54 | * if setup fails 55 | */ 56 | protected void setUp() throws Throwable { 57 | } 58 | 59 | /** 60 | * Override to tear down your specific external resource. 61 | * 62 | * @throws Throwable 63 | * if teardown fails 64 | */ 65 | protected void tearDown() throws Throwable { 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/example/model/Widget.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 15, 2009 8 | */ 9 | package com.example.model; 10 | 11 | import java.io.Serializable; 12 | 13 | import javax.persistence.Column; 14 | import javax.persistence.Entity; 15 | import javax.persistence.Id; 16 | import javax.persistence.NamedQueries; 17 | import javax.persistence.NamedQuery; 18 | 19 | /** 20 | * @author Alistair A. Israel 21 | */ 22 | @Entity 23 | @NamedQueries({ 24 | @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"), 25 | @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"), 26 | @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name") 27 | }) 28 | public class Widget implements Serializable { 29 | 30 | /** 31 | * 32 | */ 33 | private static final long serialVersionUID = -1689099836716604893L; 34 | 35 | /** 36 | * {@value #LIST_ALL} 37 | */ 38 | public static final String LIST_ALL = "Widget.listAll"; 39 | 40 | /** 41 | * {@value #FIND_BY_ID} 42 | */ 43 | public static final String FIND_BY_ID = "Widget.findById"; 44 | 45 | /** 46 | * {@value #FIND_BY_NAME} 47 | */ 48 | public static final String FIND_BY_NAME = "Widget.findByName"; 49 | 50 | @Id 51 | private Integer id; 52 | 53 | @Column 54 | private String name; 55 | 56 | /** 57 | * @return the id 58 | */ 59 | public final Integer getId() { 60 | return id; 61 | } 62 | 63 | /** 64 | * @param id 65 | * the id to set 66 | */ 67 | public final void setId(final Integer id) { 68 | this.id = id; 69 | } 70 | 71 | /** 72 | * @return the name 73 | */ 74 | public final String getName() { 75 | return name; 76 | } 77 | 78 | /** 79 | * @param name 80 | * the name to set 81 | */ 82 | public final void setName(final String name) { 83 | this.name = name; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/ExpectedExceptions.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 5, 2011 8 | */ 9 | package junit.rules; 10 | 11 | import static junit.framework.Assert.fail; 12 | 13 | import java.lang.reflect.Method; 14 | 15 | import org.junit.rules.TestRule; 16 | import org.junit.runner.Description; 17 | import org.junit.runners.model.Statement; 18 | 19 | /** 20 | * @author Alistair A. Israel 21 | * @since 0.5.1 22 | */ 23 | public class ExpectedExceptions implements TestRule { 24 | 25 | /** 26 | * {@inheritDoc} 27 | * 28 | * @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement, org.junit.runner.Description) 29 | */ 30 | @Override 31 | public final Statement apply(final Statement base, final Description description) { 32 | final Class testClass = description.getTestClass(); 33 | final String methodName = description.getMethodName(); 34 | try { 35 | final Method method = testClass.getMethod(methodName); 36 | if (method == null) { 37 | fail("getMethod(\"" + methodName + "\") returned null!"); 38 | } 39 | final Throws throwsAnnotation = method.getAnnotation(Throws.class); 40 | if (throwsAnnotation == null) { 41 | return base; 42 | } 43 | final Class expected = throwsAnnotation.value(); 44 | return new Statement() { 45 | @Override 46 | public void evaluate() throws Throwable { 47 | try { 48 | base.evaluate(); 49 | fail("Expected exception " + expected.getName() + " not thrown!"); 50 | } catch (final Throwable t) { 51 | if (!expected.isInstance(t)) { 52 | throw t; 53 | } 54 | } 55 | } 56 | }; 57 | } catch (final SecurityException e) { 58 | throw new RuntimeException(e); 59 | } catch (final NoSuchMethodException e) { 60 | throw new RuntimeException(e); 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/cdi/Weld.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Feb 15, 2011 8 | */ 9 | package junit.rules.cdi; 10 | 11 | import javax.enterprise.context.spi.CreationalContext; 12 | import javax.enterprise.inject.spi.AnnotatedType; 13 | import javax.enterprise.inject.spi.BeanManager; 14 | import javax.enterprise.inject.spi.InjectionTarget; 15 | 16 | import org.jboss.weld.environment.se.WeldContainer; 17 | import org.junit.rules.MethodRule; 18 | import org.junit.runners.model.FrameworkMethod; 19 | import org.junit.runners.model.Statement; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | /** 24 | * Provides a CDI (JSR-299) test environment using JBoss Weld. 25 | * 26 | * @author Alistair A. Israel 27 | */ 28 | @SuppressWarnings("deprecation") 29 | public class Weld implements MethodRule { 30 | 31 | private static final Logger logger = LoggerFactory.getLogger(Weld.class); 32 | 33 | private final org.jboss.weld.environment.se.Weld weld; 34 | 35 | private WeldContainer weldContainer; 36 | 37 | /** 38 | * 39 | */ 40 | public Weld() { 41 | logger.trace("Weld()"); 42 | weld = new org.jboss.weld.environment.se.Weld(); 43 | weldContainer = weld.initialize(); 44 | } 45 | 46 | /** 47 | * {@inheritDoc} 48 | * 49 | * @see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, 50 | * org.junit.runners.model.FrameworkMethod, java.lang.Object) 51 | */ 52 | @Override 53 | public final Statement apply(final Statement base, final FrameworkMethod method, 54 | final Object target) { 55 | logger.trace("apply({}.{})", method.getMethod().getDeclaringClass().getCanonicalName(), 56 | method.getName()); 57 | final BeanManager bm = weldContainer.getBeanManager(); 58 | final Class cl = target.getClass(); 59 | @SuppressWarnings("unchecked") 60 | final AnnotatedType at = (AnnotatedType) bm.createAnnotatedType(cl); 61 | final InjectionTarget it = bm.createInjectionTarget(at); 62 | return new Statement() { 63 | @Override 64 | public void evaluate() throws Throwable { 65 | // before 66 | final CreationalContext cc = bm.createCreationalContext(null); 67 | it.inject(target, cc); 68 | 69 | // yield 70 | base.evaluate(); 71 | 72 | // after 73 | weld.shutdown(); 74 | } 75 | }; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/dbunit/DbUnitUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package junit.rules.dbunit; 10 | 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.io.InputStream; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | import org.dbunit.dataset.IDataSet; 18 | import org.dbunit.dataset.xml.XmlDataSet; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | /** 23 | * @author Alistair A. Israel 24 | */ 25 | public final class DbUnitUtil { 26 | 27 | private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class); 28 | 29 | /** 30 | * Utility classes should not have a public or default constructor. 31 | */ 32 | private DbUnitUtil() { 33 | // noop 34 | } 35 | 36 | /** 37 | * @param fixtureNames 38 | * the fixture names 39 | * @return IDataSet[] 40 | */ 41 | public static IDataSet[] loadDataSets(final List fixtureNames) { 42 | final List dataSets = new ArrayList(); 43 | 44 | for (final String fixtureName : fixtureNames) { 45 | LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\""); 46 | final IDataSet dataSet = attemptToLoadFixture(fixtureName); 47 | if (dataSet != null) { 48 | dataSets.add(dataSet); 49 | } 50 | } 51 | 52 | return dataSets.toArray(new IDataSet[dataSets.size()]); 53 | } 54 | 55 | /** 56 | * @param fixtureName 57 | * the fixture name 58 | * @return {@link IDataSet} 59 | */ 60 | private static IDataSet attemptToLoadFixture(final String fixtureName) { 61 | IDataSet dataSet = null; 62 | 63 | try { 64 | final InputStream in = new FileInputStream(getFile(fixtureName)); 65 | try { 66 | if (in != null) { 67 | if (fixtureName.endsWith(".xml")) { 68 | dataSet = new XmlDataSet(in); 69 | } 70 | } 71 | } finally { 72 | in.close(); 73 | } 74 | } catch (final Exception e) { 75 | throw new Error(e.getMessage(), e); 76 | } 77 | return dataSet; 78 | } 79 | 80 | /** 81 | * @param fixtureName 82 | * the fixture (file) name 83 | * @return the {@link File} with the prefix 84 | */ 85 | public static File getFile(final String fixtureName) { 86 | return new File("src/test/db/fixtures", fixtureName); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/jndi/StubJndiContextTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Jun 2, 2011 8 | */ 9 | package junit.rules.jndi; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | import static org.junit.Assert.assertTrue; 14 | 15 | import java.lang.reflect.InvocationHandler; 16 | import java.lang.reflect.Method; 17 | import java.lang.reflect.Proxy; 18 | 19 | import javax.naming.InitialContext; 20 | import javax.sql.DataSource; 21 | 22 | import org.junit.Before; 23 | import org.junit.Rule; 24 | import org.junit.Test; 25 | import org.junit.runner.JUnitCore; 26 | import org.junit.runner.Result; 27 | 28 | /** 29 | * JUnit test for {@link StubJndiContext}. 30 | * 31 | * @author Alistair A. Israel 32 | */ 33 | public final class StubJndiContextTest { 34 | 35 | /** 36 | * Test using {@link StubJndiContext} 37 | */ 38 | public static final class TestUsingStubJndi { 39 | 40 | /** 41 | * The {@link StubJndiContext} rule 42 | */ 43 | @Rule 44 | // SUPPRESS CHECKSTYLE VisibilityModifier 45 | public StubJndiContext stubJndiContext = new StubJndiContext(); 46 | 47 | /** 48 | * 49 | */ 50 | @Before 51 | public void setUp() { 52 | // bind a DataSource proxy that does nothing 53 | stubJndiContext.bind("jdbc/dataSource", Proxy.newProxyInstance(DataSource.class.getClassLoader(), 54 | new Class[] { DataSource.class }, new InvocationHandler() { 55 | 56 | @Override 57 | public Object invoke(final Object proxy, final Method method, final Object[] args) 58 | throws Throwable { 59 | throw new UnsupportedOperationException("Not yet implemented"); 60 | } 61 | })); 62 | } 63 | 64 | /** 65 | * @throws Exception 66 | * should never happen 67 | */ 68 | @Test 69 | public void testJndi() throws Exception { 70 | final InitialContext ic = new InitialContext(); 71 | assertNotNull(ic); 72 | final Object obj = ic.lookup("jdbc/dataSource"); 73 | assertNotNull(obj); 74 | assertTrue(obj instanceof DataSource); 75 | } 76 | } 77 | 78 | /** 79 | * 80 | */ 81 | @Test 82 | public void testUsingStubJndi() { 83 | final Result result = JUnitCore.runClasses(TestUsingStubJndi.class); 84 | assertEquals(0, result.getFailureCount()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/cdi/WeldTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Feb 15, 2011 8 | */ 9 | package junit.rules.cdi; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | import static org.junit.Assert.assertTrue; 14 | 15 | import javax.inject.Inject; 16 | 17 | import org.junit.Rule; 18 | import org.junit.Test; 19 | import org.junit.runner.JUnitCore; 20 | import org.junit.runner.Result; 21 | import org.junit.runner.notification.Failure; 22 | 23 | /** 24 | * The Class WeldTest. 25 | * 26 | * @author Alistair A. Israel 27 | */ 28 | public final class WeldTest { 29 | 30 | /** 31 | * Illustrates how one would use the Weld {@code @Rule}. 32 | * 33 | * @author Alistair A. Israel 34 | */ 35 | public static final class UsesWeldTest { 36 | 37 | /** The weld. */ 38 | @Rule 39 | // CHECKSTYLE:OFF 40 | public Weld weld = new Weld(); 41 | // CHECKSTYLE:ON 42 | 43 | @Inject 44 | private ClassUnderTest classUnderTest; 45 | 46 | /** 47 | * Test injection. 48 | */ 49 | @Test 50 | public void testInjection() { 51 | assertNotNull(classUnderTest); 52 | assertNotNull(classUnderTest.dependency); 53 | assertTrue(classUnderTest.dependency instanceof MockDependency); 54 | } 55 | } 56 | 57 | /** 58 | * Test Weld {@code @Rule} using {@link UsesWeldTest}. 59 | */ 60 | @Test 61 | public void testWeld() { 62 | final Result result = JUnitCore.runClasses(UsesWeldTest.class); 63 | final int failureCount = result.getFailureCount(); 64 | assertEquals(0, failureCount); 65 | if (failureCount != 0) { 66 | System.out.println("Encountered " + failureCount + " failures"); 67 | for (final Failure failure : result.getFailures()) { 68 | System.out.println(failure); 69 | final Throwable e = failure.getException(); 70 | if (e != null) { 71 | e.printStackTrace(); 72 | } 73 | } 74 | } 75 | } 76 | 77 | /** 78 | * The class ClassUnderTest. 79 | */ 80 | public static class ClassUnderTest { 81 | @Inject 82 | private Dependency dependency; 83 | 84 | } 85 | 86 | /** 87 | * The interface Dependency. 88 | */ 89 | public interface Dependency { 90 | 91 | } 92 | 93 | /** 94 | * The default implementation of Dependency. 95 | */ 96 | public static class DependencyImpl implements Dependency { 97 | 98 | } 99 | 100 | /** 101 | * The mock implementation of Dependency, which is what we're interested in. 102 | */ 103 | @Mock 104 | public static class MockDependency implements Dependency { 105 | 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/jpa/hibernate/DerbyHibernateTestCaseTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 15, 2009 8 | */ 9 | package junit.rules.jpa.hibernate; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | import static org.junit.Assert.assertTrue; 14 | 15 | import java.util.List; 16 | 17 | import junit.rules.dbunit.Fixtures; 18 | 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.junit.runner.JUnitCore; 22 | import org.junit.runner.Result; 23 | 24 | import com.example.ejb3.beans.WidgetBean; 25 | import com.example.model.Widget; 26 | 27 | /** 28 | * @author Alistair A. Israel 29 | * @since 0.3 30 | */ 31 | public final class DerbyHibernateTestCaseTest { 32 | 33 | /** 34 | * @author Alistair A. Israel 35 | */ 36 | @Fixtures("fixtures.xml") 37 | public static final class FirstTest extends DerbyHibernateTestCase { 38 | 39 | private WidgetBean widgetBean = new WidgetBean(); 40 | 41 | /** 42 | * 43 | */ 44 | @Before 45 | public void setUp() { 46 | injectAndPostConstruct(widgetBean); 47 | } 48 | 49 | /** 50 | * @throws Exception 51 | * on exception 52 | */ 53 | @Test 54 | public void testListAll() throws Exception { 55 | final List widgets = widgetBean.listAll(); 56 | assertNotNull(widgets); 57 | assertEquals(2, widgets.size()); 58 | } 59 | 60 | /** 61 | * @throws Exception 62 | * on exception 63 | */ 64 | @Test 65 | public void testFindById() throws Exception { 66 | final Widget widget = widgetBean.findById(2); 67 | assertNotNull(widget); 68 | assertEquals(2, widget.getId().intValue()); 69 | } 70 | } 71 | 72 | /** 73 | * 74 | */ 75 | @Test 76 | public void testRunFirst() { 77 | final Result results = JUnitCore.runClasses(FirstTest.class); 78 | assertTrue(results.wasSuccessful()); 79 | } 80 | 81 | /** 82 | * @author Alistair A. Israel 83 | */ 84 | @Fixtures("fixtures.xml") 85 | public static final class SecondTest extends DerbyHibernateTestCase { 86 | 87 | private WidgetBean widgetBean = new WidgetBean(); 88 | 89 | /** 90 | * @throws Exception 91 | * on exception 92 | */ 93 | @Test 94 | public void testListAll() throws Exception { 95 | injectAndPostConstruct(widgetBean); 96 | final List widgets = widgetBean.listAll(); 97 | assertNotNull(widgets); 98 | assertEquals(2, widgets.size()); 99 | } 100 | } 101 | 102 | /** 103 | * 104 | */ 105 | @Test 106 | public void testRunFirstAndSecond() { 107 | final Result results = JUnitCore.runClasses(FirstTest.class, SecondTest.class); 108 | assertTrue(results.wasSuccessful()); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/dbunit/DbUnitTestFixtures.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 19, 2009 8 | */ 9 | package junit.rules.dbunit; 10 | 11 | import static junit.rules.dbunit.FixturesUtil.getFixtureNames; 12 | 13 | import java.lang.reflect.Method; 14 | import java.util.List; 15 | 16 | import junit.rules.TestFixture; 17 | import junit.rules.util.Reflection; 18 | 19 | import org.apache.derby.jdbc.EmbeddedDriver; 20 | import org.dbunit.JdbcDatabaseTester; 21 | import org.dbunit.dataset.CompositeDataSet; 22 | import org.dbunit.dataset.DataSetException; 23 | import org.dbunit.dataset.IDataSet; 24 | import org.junit.runner.Description; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | /** 29 | * @author Alistair A. Israel 30 | */ 31 | public class DbUnitTestFixtures extends TestFixture { 32 | 33 | private static final Logger logger = LoggerFactory.getLogger(DbUnitTestFixtures.class); 34 | 35 | private List fixtureNames; 36 | 37 | private JdbcDatabaseTester tester; 38 | 39 | /** 40 | * Default constructor. Will use a hard-coded Derby 'test' database. 41 | */ 42 | public DbUnitTestFixtures() { 43 | // noop 44 | } 45 | 46 | /** 47 | * @param jdbcDatabaseTester 48 | * the {@link JdbcDatabaseTester} to use 49 | */ 50 | public DbUnitTestFixtures(final JdbcDatabaseTester jdbcDatabaseTester) { 51 | this.tester = jdbcDatabaseTester; 52 | } 53 | 54 | /** 55 | * {@inheritDoc} 56 | * 57 | * @see junit.rules.TestFixture#inspect(org.junit.runner.Description) 58 | */ 59 | @Override 60 | protected final void inspect(final Description description) { 61 | final Class testClass = description.getTestClass(); 62 | final Method method = Reflection.quietlyGetMethod(testClass, description.getMethodName()); 63 | fixtureNames = getFixtureNames(testClass, method); 64 | } 65 | 66 | /** 67 | * {@inheritDoc} 68 | * 69 | * @see junit.rules.TestFixture#setUp() 70 | */ 71 | @Override 72 | protected final void setUp() throws Throwable { 73 | if (tester == null) { 74 | tester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), "jdbc:derby:test"); 75 | } 76 | if (fixtureNames.isEmpty()) { 77 | logger.warn("No fixtures to load! Specify fixtures using @Fixtures."); 78 | } else { 79 | try { 80 | final IDataSet[] dataSets = DbUnitUtil.loadDataSets(fixtureNames); 81 | final CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets); 82 | tester.setDataSet(compositeDataSet); 83 | } catch (final DataSetException e) { 84 | throw new Error(e.getMessage(), e); 85 | } 86 | } 87 | 88 | tester.onSetup(); 89 | } 90 | 91 | /** 92 | * {@inheritDoc} 93 | * 94 | * @see junit.rules.TestFixture#tearDown() 95 | */ 96 | @Override 97 | protected final void tearDown() throws Throwable { 98 | tester.onTearDown(); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jetty/SimpleJettyHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Apr 26, 2011 8 | */ 9 | package junit.rules.jetty; 10 | 11 | import java.io.IOException; 12 | import java.io.PrintWriter; 13 | 14 | import javax.servlet.ServletException; 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | 18 | import org.mortbay.jetty.handler.AbstractHandler; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | /** 23 | * @author Alistair A. Israel 24 | */ 25 | public class SimpleJettyHandler extends AbstractHandler { 26 | 27 | private static final Logger logger = LoggerFactory.getLogger(SimpleJettyHandler.class); 28 | 29 | /** 30 | * {@value #GET} 31 | */ 32 | private static final String GET = "GET"; 33 | 34 | /** 35 | * {@value #POST} 36 | */ 37 | private static final String POST = "POST"; 38 | 39 | /** 40 | * {@value #PUT} 41 | */ 42 | private static final String PUT = "PUT"; 43 | 44 | /** 45 | * {@value #DELETE} 46 | */ 47 | private static final String DELETE = "DELETE"; 48 | 49 | private HttpServletRequest httpServletRequest; 50 | 51 | private HttpServletResponse httpServletResponse; 52 | 53 | private PrintWriter responseWriter; 54 | 55 | private int responseCodeSent; 56 | 57 | /** 58 | * {@inheritDoc} 59 | * 60 | * @see org.mortbay.jetty.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, 61 | * javax.servlet.http.HttpServletResponse, int) 62 | */ 63 | @Override 64 | public final void handle(final String target, final HttpServletRequest request, final HttpServletResponse response, 65 | final int dispatch) throws IOException, ServletException { 66 | responseCodeSent = -1; 67 | httpServletRequest = request; 68 | httpServletResponse = response; 69 | responseWriter = response.getWriter(); 70 | final String requestMethod = request.getMethod(); 71 | logger.debug(requestMethod + " " + request.getRequestURI()); 72 | if (GET.equalsIgnoreCase(requestMethod)) { 73 | onGet(); 74 | } else if (POST.equalsIgnoreCase(requestMethod)) { 75 | onPost(); 76 | } else if (PUT.equalsIgnoreCase(requestMethod)) { 77 | onPut(); 78 | } else if (DELETE.equalsIgnoreCase(requestMethod)) { 79 | onDelete(); 80 | } 81 | if (responseCodeSent == -1) { 82 | sendResponse(HttpServletResponse.SC_OK); 83 | } 84 | } 85 | 86 | /** 87 | * @return the httpServletRequest 88 | */ 89 | public final HttpServletRequest request() { 90 | return httpServletRequest; 91 | } 92 | 93 | /** 94 | * @return the httpServletResponse 95 | */ 96 | public final HttpServletResponse response() { 97 | return httpServletResponse; 98 | } 99 | 100 | /** 101 | * @return the responseWriter 102 | */ 103 | public final PrintWriter getResponseWriter() { 104 | return responseWriter; 105 | } 106 | 107 | /** 108 | * @throws IOException 109 | * on exception 110 | */ 111 | protected void onGet() throws IOException { 112 | } 113 | 114 | /** 115 | * @throws IOException 116 | * on exception 117 | */ 118 | protected void onPost() throws IOException { 119 | } 120 | 121 | /** 122 | * @throws IOException 123 | * on exception 124 | */ 125 | protected void onPut() throws IOException { 126 | } 127 | 128 | /** 129 | * @throws IOException 130 | * on exception 131 | */ 132 | protected void onDelete() throws IOException { 133 | } 134 | 135 | /** 136 | * @param responseCode 137 | * the HTTP response code to send 138 | * @throws IOException 139 | * on exception 140 | */ 141 | protected final void sendResponse(final int responseCode) throws IOException { 142 | responseWriter.flush(); 143 | httpServletResponse.setStatus(responseCode); 144 | httpServletResponse.flushBuffer(); 145 | responseCodeSent = responseCode; 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jetty/JettyServerRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 3, 2009 8 | */ 9 | package junit.rules.jetty; 10 | 11 | import java.io.IOException; 12 | import java.net.HttpURLConnection; 13 | import java.net.InetSocketAddress; 14 | import java.net.URL; 15 | 16 | import junit.rules.httpserver.BaseHttpServerRule; 17 | 18 | import org.mortbay.jetty.Handler; 19 | import org.mortbay.jetty.Server; 20 | 21 | /** 22 | * @author Alistair A. Israel 23 | */ 24 | public class JettyServerRule extends BaseHttpServerRule { 25 | 26 | private final int port; 27 | 28 | private Server server; 29 | 30 | /** 31 | * 32 | */ 33 | public JettyServerRule() { 34 | this(DEFAULT_HTTP_PORT); 35 | } 36 | 37 | /** 38 | * @param port 39 | * the port to listen (HTTP) on 40 | */ 41 | public JettyServerRule(final int port) { 42 | this.port = port; 43 | } 44 | 45 | /** 46 | * @return the port 47 | */ 48 | public final int getPort() { 49 | return port; 50 | } 51 | 52 | /** 53 | * {@inheritDoc} 54 | * 55 | * @see org.junit.rules.ExternalResource#before() 56 | */ 57 | @Override 58 | protected final void setUp() throws Throwable { 59 | server = new Server(port); 60 | server.start(); 61 | } 62 | 63 | /** 64 | * @param handler 65 | * {@link Handler} 66 | * @see org.mortbay.jetty.handler.HandlerWrapper#setHandler(org.mortbay.jetty.Handler) 67 | */ 68 | public final void setHandler(final Handler handler) { 69 | server.setHandler(handler); 70 | } 71 | 72 | /** 73 | * {@inheritDoc} 74 | * 75 | * @see org.junit.rules.ExternalResource#after() 76 | */ 77 | @Override 78 | protected final void tearDown() throws Throwable { 79 | server.stop(); 80 | } 81 | 82 | /** 83 | * @param path 84 | * the URI path to GET 85 | * @return the HttpURLConnection 86 | * @throws IOException 87 | * on exception 88 | */ 89 | @Override 90 | public final HttpURLConnection get(final String path) throws IOException { 91 | final InetSocketAddress address = new InetSocketAddress(getPort()); 92 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 93 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 94 | connection.setRequestMethod("GET"); 95 | connection.connect(); 96 | return connection; 97 | } 98 | 99 | /** 100 | * @param path 101 | * the URI path to POST to 102 | * @return the HttpURLConnection 103 | * @throws IOException 104 | * on exception 105 | */ 106 | @Override 107 | public final HttpURLConnection post(final String path) throws IOException { 108 | final InetSocketAddress address = new InetSocketAddress(getPort()); 109 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 110 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 111 | connection.setDoOutput(true); 112 | connection.setRequestMethod("POST"); 113 | connection.connect(); 114 | return connection; 115 | } 116 | 117 | /** 118 | * @param path 119 | * the URI path to PUT to 120 | * @return the HttpURLConnection 121 | * @throws IOException 122 | * on exception 123 | */ 124 | @Override 125 | public final HttpURLConnection put(final String path) throws IOException { 126 | final InetSocketAddress address = new InetSocketAddress(getPort()); 127 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 128 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 129 | connection.setDoOutput(true); 130 | connection.setRequestMethod("PUT"); 131 | connection.connect(); 132 | return connection; 133 | } 134 | 135 | /** 136 | * @param path 137 | * the URI path to DELETE 138 | * @return the HttpURLConnection 139 | * @throws IOException 140 | * on exception 141 | */ 142 | @Override 143 | public final HttpURLConnection delete(final String path) throws IOException { 144 | final InetSocketAddress address = new InetSocketAddress(getPort()); 145 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 146 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 147 | connection.setRequestMethod("DELETE"); 148 | connection.connect(); 149 | return connection; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/httpserver/HttpServerRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Aug 28, 2009 8 | */ 9 | package junit.rules.httpserver; 10 | 11 | import java.io.IOException; 12 | import java.net.HttpURLConnection; 13 | import java.net.InetSocketAddress; 14 | import java.net.URL; 15 | 16 | import com.sun.net.httpserver.HttpHandler; 17 | import com.sun.net.httpserver.HttpServer; 18 | 19 | /** 20 | * 21 | * @author Alistair A. Israel 22 | */ 23 | public class HttpServerRule extends BaseHttpServerRule { 24 | 25 | private final InetSocketAddress address; 26 | 27 | private HttpServer httpServer; 28 | 29 | /** 30 | * 31 | */ 32 | public HttpServerRule() { 33 | this(DEFAULT_HTTP_PORT); 34 | } 35 | 36 | /** 37 | * @param port 38 | * the port to listen (HTTP) on 39 | */ 40 | public HttpServerRule(final int port) { 41 | this(new InetSocketAddress(port)); 42 | } 43 | 44 | /** 45 | * @param address 46 | * {@link InetSocketAddress} 47 | */ 48 | public HttpServerRule(final InetSocketAddress address) { 49 | this.address = address; 50 | } 51 | 52 | /** 53 | * @return the address 54 | */ 55 | public final InetSocketAddress getAddress() { 56 | return address; 57 | } 58 | 59 | /** 60 | * @param path 61 | * the root URI path to associate the context with 62 | * @param handler 63 | * the handler to invoke for incoming requests 64 | */ 65 | public final void addHandler(final String path, final HttpHandler handler) { 66 | httpServer.createContext(path, handler); 67 | } 68 | 69 | /** 70 | * {@inheritDoc} 71 | * 72 | * @see junit.rules.TestFixture#setUp() 73 | */ 74 | @Override 75 | protected final void setUp() throws Throwable { 76 | httpServer = HttpServer.create(address, 0); 77 | httpServer.start(); 78 | } 79 | 80 | /** 81 | * {@inheritDoc} 82 | * 83 | * @see junit.rules.TestFixture#tearDown() 84 | */ 85 | @Override 86 | protected final void tearDown() throws Throwable { 87 | httpServer.stop(0); 88 | } 89 | 90 | /** 91 | * @param path 92 | * the URI path to GET 93 | * @return the HttpURLConnection 94 | * @throws IOException 95 | * on exception 96 | */ 97 | @Override 98 | public final HttpURLConnection get(final String path) throws IOException { 99 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 100 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 101 | connection.setRequestMethod("GET"); 102 | connection.connect(); 103 | return connection; 104 | } 105 | 106 | /** 107 | * @param path 108 | * the URI path to POST to 109 | * @return the HttpURLConnection 110 | * @throws IOException 111 | * on exception 112 | */ 113 | @Override 114 | public final HttpURLConnection post(final String path) throws IOException { 115 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 116 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 117 | connection.setDoOutput(true); 118 | connection.setRequestMethod("POST"); 119 | connection.connect(); 120 | return connection; 121 | } 122 | 123 | /** 124 | * @param path 125 | * the URI path to PUT to 126 | * @return the HttpURLConnection 127 | * @throws IOException 128 | * on exception 129 | */ 130 | @Override 131 | public final HttpURLConnection put(final String path) throws IOException { 132 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 133 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 134 | connection.setDoOutput(true); 135 | connection.setRequestMethod("PUT"); 136 | connection.connect(); 137 | return connection; 138 | } 139 | 140 | /** 141 | * @param path 142 | * the URI path to DELETE 143 | * @return the HttpURLConnection 144 | * @throws IOException 145 | * on exception 146 | */ 147 | @Override 148 | public final HttpURLConnection delete(final String path) throws IOException { 149 | final URL url = new URL("http://" + address.getHostName() + ":" + address.getPort() + path); 150 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 151 | connection.setRequestMethod("DELETE"); 152 | connection.connect(); 153 | return connection; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/jetty/JettyServerRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Aug 28, 2009 8 | */ 9 | package junit.rules.jetty; 10 | 11 | import static java.lang.Boolean.FALSE; 12 | import static java.lang.Boolean.TRUE; 13 | import static java.net.HttpURLConnection.HTTP_OK; 14 | import static org.junit.Assert.assertEquals; 15 | import static org.junit.Assert.assertTrue; 16 | 17 | import java.io.BufferedReader; 18 | import java.io.BufferedWriter; 19 | import java.io.IOException; 20 | import java.io.InputStreamReader; 21 | import java.io.OutputStreamWriter; 22 | import java.io.PrintWriter; 23 | import java.net.HttpURLConnection; 24 | 25 | import junit.rules.util.SimpleReference; 26 | 27 | import org.junit.Rule; 28 | import org.junit.Test; 29 | 30 | /** 31 | *

32 | * JUnit test case for {@link JettyServerRule}. 33 | *

34 | *

35 | * With contributions by Sam Tunnicliffe. 36 | *

37 | * 38 | * @author Alistair A. Israel 39 | */ 40 | public final class JettyServerRuleTest { 41 | 42 | // CHECKSTYLE:OFF 43 | @Rule 44 | public final JettyServerRule jettyServer = new JettyServerRule(); 45 | 46 | // CHECKSTYLE:ON 47 | 48 | /** 49 | * @throws Exception 50 | * on exception 51 | */ 52 | @Test 53 | public void testJettyServerRule() throws Exception { 54 | jettyServer.setHandler(new SimpleJettyHandler() { 55 | @Override 56 | protected void onGet() throws IOException { 57 | final PrintWriter out = getResponseWriter(); 58 | out.println(""); 59 | out.println(""); 60 | } 61 | }); 62 | 63 | final HttpURLConnection connection = jettyServer.get("/1234.xml"); 64 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 65 | assertEquals("", in.readLine()); 66 | assertEquals("", in.readLine()); 67 | assertEquals(HTTP_OK, connection.getResponseCode()); 68 | } 69 | 70 | /** 71 | * Test HTTP POST 72 | * 73 | * @throws Exception 74 | * should never happen 75 | */ 76 | @Test 77 | public void testJettyServerRulePostMethod() throws Exception { 78 | jettyServer.setHandler(new SimpleJettyHandler() { 79 | @Override 80 | protected void onPost() throws IOException { 81 | final BufferedReader reader = new BufferedReader(new InputStreamReader(request().getInputStream())); 82 | final PrintWriter out = getResponseWriter(); 83 | out.println(reader.readLine()); 84 | } 85 | }); 86 | final HttpURLConnection connection = jettyServer.post("/"); 87 | final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 88 | out.write("Hello World"); 89 | out.flush(); 90 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 91 | assertEquals("Hello World", in.readLine()); 92 | assertEquals(HTTP_OK, connection.getResponseCode()); 93 | } 94 | 95 | /** 96 | * Test HTTP PUT 97 | * 98 | * @throws Exception 99 | * should never happen 100 | */ 101 | @Test 102 | public void testJettyServerRulePutMethod() throws Exception { 103 | jettyServer.setHandler(new SimpleJettyHandler() { 104 | @Override 105 | protected void onPut() throws IOException { 106 | final BufferedReader reader = new BufferedReader(new InputStreamReader(request().getInputStream())); 107 | final PrintWriter out = getResponseWriter(); 108 | out.println(reader.readLine()); 109 | } 110 | }); 111 | final HttpURLConnection connection = jettyServer.put("/"); 112 | final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 113 | out.write("Hello Again"); 114 | out.flush(); 115 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 116 | assertEquals("Hello Again", in.readLine()); 117 | assertEquals(HTTP_OK, connection.getResponseCode()); 118 | } 119 | 120 | /** 121 | * Test HTTP DELETE 122 | * 123 | * @throws Exception 124 | * should never happen 125 | */ 126 | @Test 127 | public void testJettyServerRuleDeleteMethod() throws Exception { 128 | final SimpleReference deleteIssued = SimpleReference.to(FALSE); 129 | jettyServer.setHandler(new SimpleJettyHandler() { 130 | @Override 131 | protected void onDelete() throws IOException { 132 | deleteIssued.set(TRUE); 133 | } 134 | }); 135 | final HttpURLConnection connection = jettyServer.delete("/"); 136 | assertEquals(HTTP_OK, connection.getResponseCode()); 137 | assertTrue(deleteIssued.get()); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/httpserver/HttpServerRuleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Aug 28, 2009 8 | */ 9 | package junit.rules.httpserver; 10 | 11 | import static java.lang.Boolean.FALSE; 12 | import static java.lang.Boolean.TRUE; 13 | import static java.net.HttpURLConnection.HTTP_OK; 14 | import static org.junit.Assert.assertEquals; 15 | import static org.junit.Assert.assertTrue; 16 | 17 | import java.io.BufferedReader; 18 | import java.io.BufferedWriter; 19 | import java.io.IOException; 20 | import java.io.InputStreamReader; 21 | import java.io.OutputStreamWriter; 22 | import java.io.PrintWriter; 23 | import java.net.HttpURLConnection; 24 | 25 | import junit.rules.util.SimpleReference; 26 | 27 | import org.junit.Rule; 28 | import org.junit.Test; 29 | 30 | /** 31 | *

32 | * JUnit test case for {@link HttpServerRule}. 33 | *

34 | *

35 | * With contributions by Sam Tunnicliffe. 36 | *

37 | * 38 | * @author Alistair A. Israel 39 | */ 40 | public final class HttpServerRuleTest { 41 | 42 | // CHECKSTYLE:OFF 43 | @Rule 44 | public final HttpServerRule httpServer = new HttpServerRule(); 45 | // CHECKSTYLE:ON 46 | 47 | /** 48 | * Test and illustrate basic usage (HTTP GET). 49 | * 50 | * @throws Exception 51 | * should never happen 52 | */ 53 | @Test 54 | public void testHttpServerRule() throws Exception { 55 | httpServer.addHandler("/", new SimpleHttpHandler() { 56 | @Override 57 | protected void onGet() throws IOException { 58 | final PrintWriter out = getResponseWriter(); 59 | out.println(""); 60 | out.println(""); 61 | sendResponse(HTTP_OK); 62 | } 63 | }); 64 | final HttpURLConnection connection = httpServer.get("/"); 65 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 66 | assertEquals("", in.readLine()); 67 | assertEquals("", in.readLine()); 68 | assertEquals(HTTP_OK, connection.getResponseCode()); 69 | } 70 | 71 | /** 72 | * Test HTTP POST 73 | * 74 | * @throws Exception 75 | * should never happen 76 | */ 77 | @Test 78 | public void testHttpServerRulePostMethod() throws Exception { 79 | httpServer.addHandler("/", new SimpleHttpHandler() { 80 | @Override 81 | protected void onPost() throws IOException { 82 | final BufferedReader reader = new BufferedReader(new InputStreamReader(getRequestBody())); 83 | getResponseWriter().write("Hello " + reader.readLine()); 84 | sendResponse(HTTP_OK); 85 | } 86 | }); 87 | final HttpURLConnection connection = httpServer.post("/"); 88 | final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 89 | out.write("World"); 90 | out.flush(); 91 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 92 | assertEquals("Hello World", in.readLine()); 93 | assertEquals(HTTP_OK, connection.getResponseCode()); 94 | } 95 | 96 | /** 97 | * Test HTTP PUT 98 | * 99 | * @throws Exception 100 | * should never happen 101 | */ 102 | @Test 103 | public void testHttpServerRulePutMethod() throws Exception { 104 | httpServer.addHandler("/", new SimpleHttpHandler() { 105 | @Override 106 | protected void onPut() throws IOException { 107 | final BufferedReader reader = new BufferedReader(new InputStreamReader(getRequestBody())); 108 | getResponseWriter().write("Hello " + reader.readLine()); 109 | sendResponse(HTTP_OK); 110 | } 111 | }); 112 | final HttpURLConnection connection = httpServer.put("/"); 113 | final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 114 | out.write("Again"); 115 | out.flush(); 116 | final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 117 | assertEquals("Hello Again", in.readLine()); 118 | assertEquals(HTTP_OK, connection.getResponseCode()); 119 | } 120 | 121 | /** 122 | * Test HTTP DELETE 123 | * 124 | * @throws Exception 125 | * should never happen 126 | */ 127 | @Test 128 | public void testHttpServerRuleDeleteMethod() throws Exception { 129 | final SimpleReference deleteIssued = SimpleReference.to(FALSE); 130 | httpServer.addHandler("/", new SimpleHttpHandler() { 131 | @Override 132 | protected void onDelete() throws IOException { 133 | deleteIssued.set(TRUE); 134 | sendResponse(HTTP_OK); 135 | } 136 | }); 137 | final HttpURLConnection connection = httpServer.delete("/"); 138 | assertEquals(HTTP_OK, connection.getResponseCode()); 139 | assertTrue(deleteIssued.get()); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /etc/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /src/test/java/junit/rules/ExpectedExceptionsTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 5, 2011 8 | */ 9 | package junit.rules; 10 | 11 | import static junit.framework.Assert.fail; 12 | import static org.junit.Assert.assertEquals; 13 | import static org.junit.Assert.assertNotNull; 14 | import static org.junit.Assert.assertTrue; 15 | import junit.framework.AssertionFailedError; 16 | 17 | import org.junit.Rule; 18 | import org.junit.Test; 19 | import org.junit.runner.JUnitCore; 20 | import org.junit.runner.Result; 21 | import org.junit.runner.notification.Failure; 22 | 23 | /** 24 | * JUnit test for {@link ExpectedExceptions} 25 | * 26 | * @author Alistair A. Israel 27 | */ 28 | public final class ExpectedExceptionsTest { 29 | 30 | /** 31 | * Run test using {@link UsesExpectedExceptions} 32 | */ 33 | @Test 34 | public void testExpectedExceptions() { 35 | runTestClassExpectOneFailure(UsesExpectedExceptions.class, new FailureCallback() { 36 | @Override 37 | public void callback(final Failure failure) { 38 | final Throwable e = failure.getException(); 39 | assertNotNull(e); 40 | assertTrue(e instanceof ArrayIndexOutOfBoundsException); 41 | } 42 | }); 43 | } 44 | 45 | /** 46 | * Run test {@link ExpectsExceptionButNoneThrown} 47 | */ 48 | @Test 49 | public void testExpectsExceptionButNoneThrown() { 50 | runTestClassExpectOneFailure(ExpectsExceptionButNoneThrown.class, new FailureCallback() { 51 | @Override 52 | public void callback(final Failure failure) { 53 | final Throwable e = failure.getException(); 54 | assertNotNull(e); 55 | assertTrue(e instanceof AssertionFailedError); 56 | assertEquals("Expected exception java.lang.NullPointerException not thrown!", e.getMessage()); 57 | } 58 | }); 59 | } 60 | 61 | /** 62 | * Expects one failure. 63 | * 64 | * @author Alistair A. Israel 65 | */ 66 | private interface FailureCallback { 67 | 68 | /** 69 | * @param failure 70 | * the Failure 71 | */ 72 | void callback(Failure failure); 73 | } 74 | 75 | /** 76 | * @param testClass 77 | * the test class 78 | * @param callback 79 | * the {@link FailureCallback} 80 | */ 81 | private static void runTestClassExpectOneFailure(final Class testClass, final FailureCallback callback) { 82 | final Result result = JUnitCore.runClasses(testClass); 83 | final int failureCount = result.getFailureCount(); 84 | if (failureCount == 1) { 85 | final Failure failure = result.getFailures().get(0); 86 | callback.callback(failure); 87 | } else { 88 | System.out.println("Encountered " + failureCount + " failures, expecting only 1"); 89 | for (final Failure failure : result.getFailures()) { 90 | System.out.println(failure); 91 | final Throwable e = failure.getException(); 92 | if (e != null) { 93 | e.printStackTrace(); 94 | } 95 | } 96 | fail("Encountered " + failureCount + " failures, expecting only 1"); 97 | } 98 | } 99 | 100 | /** 101 | * A sample unit test that uses {@link ExpectedExceptions} rule. 102 | * 103 | * @author Alistair A. Israel 104 | */ 105 | public static final class UsesExpectedExceptions { 106 | 107 | /** 108 | * The rule 109 | */ 110 | @Rule 111 | // SUPPRESS CHECKSTYLE VisibilityModifier 112 | public final ExpectedExceptions expectedExceptions = new ExpectedExceptions(); 113 | 114 | /** 115 | * No exception and no annotation 116 | */ 117 | @Test 118 | public void noException() { 119 | assertTrue("Should be true", true); 120 | } 121 | 122 | /** 123 | * This test should fail, since we're saying we expect a {@link NullPointerException} but the code throws an 124 | * {@link ArrayIndexOutOfBoundsException}. 125 | */ 126 | @Test 127 | @Throws(NullPointerException.class) 128 | public void throwsArrayIndexOutOfBounds() { 129 | final int[] a = {}; 130 | @SuppressWarnings("unused") 131 | final int i = a[1]; 132 | } 133 | 134 | /** 135 | * 136 | */ 137 | @Test 138 | @Throws(NullPointerException.class) 139 | @SuppressWarnings("null") 140 | public void throwsNullPointerException() { 141 | final String s = null; 142 | s.length(); 143 | } 144 | 145 | /** 146 | * Check that the message matching works. 147 | */ 148 | @Test 149 | @Throws(value = IllegalArgumentException.class, message = "x should be non-negative!") 150 | public void throwsIllegalArgumentException() { 151 | throw new IllegalArgumentException("x should be non-negative"); 152 | } 153 | } 154 | 155 | /** 156 | * Expects a {@link NullPointerException} but doesn't throw one. 157 | * 158 | * @author Alistair A. Israel 159 | */ 160 | public static final class ExpectsExceptionButNoneThrown { 161 | 162 | /** 163 | * The rule 164 | */ 165 | @Rule 166 | // SUPPRESS CHECKSTYLE VisibilityModifier 167 | public final ExpectedExceptions expectedExceptions = new ExpectedExceptions(); 168 | 169 | /** 170 | * Annotated, but no exception thrown. 171 | */ 172 | @Test 173 | @Throws(NullPointerException.class) 174 | public void noException() { 175 | assertTrue("Should be true", true); 176 | } 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 22, 2009 8 | */ 9 | package junit.rules.jpa.hibernate; 10 | 11 | import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL; 12 | import static junit.rules.util.Reflection.invoke; 13 | import static junit.rules.util.Reflection.set; 14 | 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.Method; 17 | import java.sql.DriverManager; 18 | import java.sql.SQLException; 19 | import java.util.List; 20 | 21 | import javax.annotation.PostConstruct; 22 | import javax.persistence.EntityManager; 23 | import javax.persistence.EntityManagerFactory; 24 | import javax.persistence.PersistenceContext; 25 | 26 | import junit.rules.dbunit.DbUnitUtil; 27 | import junit.rules.dbunit.FixturesUtil; 28 | 29 | import org.apache.derby.jdbc.EmbeddedDriver; 30 | import org.dbunit.JdbcDatabaseTester; 31 | import org.dbunit.dataset.CompositeDataSet; 32 | import org.dbunit.dataset.DataSetException; 33 | import org.dbunit.dataset.IDataSet; 34 | import org.hibernate.ejb.Ejb3Configuration; 35 | import org.junit.After; 36 | import org.junit.AfterClass; 37 | import org.junit.Before; 38 | import org.junit.BeforeClass; 39 | import org.slf4j.Logger; 40 | import org.slf4j.LoggerFactory; 41 | 42 | /** 43 | * @author Alistair A. Israel 44 | */ 45 | public class DerbyHibernateTestCase { 46 | 47 | private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class); 48 | 49 | private static final ThreadLocal ENTITY_MANAGER_FACTORY = new ThreadLocal(); 50 | 51 | private EntityManager entityManager; 52 | 53 | private JdbcDatabaseTester jdbcDatabaseTester; 54 | 55 | /** 56 | * 57 | */ 58 | @BeforeClass 59 | public static void initializeDerbyHibernate() { 60 | final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa(); 61 | ENTITY_MANAGER_FACTORY.set(configuration.buildEntityManagerFactory()); 62 | } 63 | 64 | /** 65 | * 66 | */ 67 | @AfterClass 68 | public static void closeHibernateDerby() { 69 | ENTITY_MANAGER_FACTORY.get().close(); 70 | try { 71 | DriverManager.getConnection(JDBC_DERBY_URL + ";shutdown=true"); 72 | } catch (final SQLException e) { 73 | if (e.getErrorCode() == 45000 && "08006".equals(e.getSQLState())) { 74 | logger.info("Derby shut down normally"); 75 | } else { 76 | // if the error code or SQLState is different, we have 77 | // an unexpected exception (shutdown failed) 78 | throw new RuntimeException(e.getMessage(), e); 79 | } 80 | } 81 | } 82 | 83 | /** 84 | * @param object 85 | * an object to which we will apply EJB 3.0 style @PersistenceContext and @PostConstruct handling 86 | */ 87 | public final void injectAndPostConstruct(final Object object) { 88 | final Class clazz = object.getClass(); 89 | for (final Field field : clazz.getDeclaredFields()) { 90 | if (field.isAnnotationPresent(PersistenceContext.class)) { 91 | final Class type = field.getType(); 92 | if (type.equals(EntityManager.class)) { 93 | set(field).of(object).to(entityManager); 94 | } else { 95 | logger.warn("Found field \"{}\" annotated with @PersistenceContext " + "but is of type {}", field 96 | .getName(), type.getName()); 97 | } 98 | } 99 | } 100 | 101 | for (final Method method : clazz.getDeclaredMethods()) { 102 | if (method.isAnnotationPresent(PostConstruct.class)) { 103 | final int nParameters = method.getParameterTypes().length; 104 | if (nParameters == 0) { 105 | invoke(method).on(object); 106 | } else { 107 | logger.warn("Found method \"{}\" annotated @PostConstruct " 108 | + "but don't know how to invoke with {} parameters", method.getName(), nParameters); 109 | } 110 | } 111 | } 112 | } 113 | 114 | /** 115 | * @throws Throwable 116 | * on any throwable 117 | */ 118 | @Before 119 | public final void initializeDbUnit() throws Throwable { 120 | entityManager = ENTITY_MANAGER_FACTORY.get().createEntityManager(); 121 | 122 | jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), JDBC_DERBY_URL); 123 | final List fixtureNames = FixturesUtil.getFixtureNames(getClass()); 124 | if (fixtureNames.isEmpty()) { 125 | logger.warn("No fixtures to load! Specify fixtures using @Fixtures."); 126 | } else { 127 | loadFixtures(fixtureNames); 128 | } 129 | 130 | jdbcDatabaseTester.onSetup(); 131 | } 132 | 133 | /** 134 | * @param fixtureNames 135 | * the fixture names 136 | * @throws DataSetException 137 | * on any exception 138 | */ 139 | private void loadFixtures(final List fixtureNames) throws DataSetException { 140 | final IDataSet[] dataSets = DbUnitUtil.loadDataSets(fixtureNames); 141 | 142 | if (dataSets.length == 0) { 143 | logger.warn("Found 0 data sets!"); 144 | } else { 145 | final CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets); 146 | jdbcDatabaseTester.setDataSet(compositeDataSet); 147 | } 148 | } 149 | 150 | /** 151 | * {@inheritDoc} 152 | * 153 | * @see junit.rules.TestFixture#tearDown() 154 | */ 155 | @After 156 | public final void tearDownDbUnit() throws Throwable { 157 | jdbcDatabaseTester.onTearDown(); 158 | } 159 | 160 | /** 161 | * @return {@link EntityManager} 162 | * @see javax.persistence.EntityManagerFactory#createEntityManager() 163 | */ 164 | public final EntityManager getEntityManager() { 165 | return this.entityManager; 166 | } 167 | 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jdbc/support/DriverManagerDataSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 5, 2011 8 | */ 9 | package junit.rules.jdbc.support; 10 | 11 | import static junit.rules.util.ObjectUtils.nullSafeEquals; 12 | import static junit.rules.util.StringUtils.hasLength; 13 | 14 | import java.io.PrintWriter; 15 | import java.sql.Connection; 16 | import java.sql.Driver; 17 | import java.sql.DriverManager; 18 | import java.sql.SQLException; 19 | import java.util.Enumeration; 20 | 21 | import javax.sql.DataSource; 22 | 23 | /** 24 | * Poor man's implementation of Spring's DriverManager-backed {@link DataSource}. 25 | * 26 | * @author Alistair.Israel 27 | */ 28 | public class DriverManagerDataSource implements DataSource { 29 | 30 | private boolean needToRegisterDriver; 31 | 32 | private String jdbcDriver; 33 | 34 | private String jdbcUrl; 35 | 36 | private String jdbcUser; 37 | 38 | private String jdbcPassword; 39 | 40 | /** 41 | * @return the jdbcDriver 42 | */ 43 | public final String getJdbcDriver() { 44 | return jdbcDriver; 45 | } 46 | 47 | /** 48 | * @param jdbcDriver 49 | * the jdbcDriver to set 50 | */ 51 | public final void setJdbcDriver(final String jdbcDriver) { 52 | if (!nullSafeEquals(this.jdbcDriver, jdbcDriver)) { 53 | this.jdbcDriver = jdbcDriver; 54 | needToRegisterDriver = true; 55 | } 56 | } 57 | 58 | /** 59 | * @return the jdbcUrl 60 | */ 61 | public final String getJdbcUrl() { 62 | return jdbcUrl; 63 | } 64 | 65 | /** 66 | * @param jdbcUrl 67 | * the jdbcUrl to set 68 | */ 69 | public final void setJdbcUrl(final String jdbcUrl) { 70 | this.jdbcUrl = jdbcUrl; 71 | } 72 | 73 | /** 74 | * @return the jdbcUser 75 | */ 76 | public final String getJdbcUser() { 77 | return jdbcUser; 78 | } 79 | 80 | /** 81 | * @param jdbcUser 82 | * the jdbcUser to set 83 | */ 84 | public final void setJdbcUser(final String jdbcUser) { 85 | this.jdbcUser = jdbcUser; 86 | } 87 | 88 | /** 89 | * @return the jdbcPassword 90 | */ 91 | public final String getJdbcPassword() { 92 | return jdbcPassword; 93 | } 94 | 95 | /** 96 | * @param jdbcPassword 97 | * the jdbcPassword to set 98 | */ 99 | public final void setJdbcPassword(final String jdbcPassword) { 100 | this.jdbcPassword = jdbcPassword; 101 | } 102 | 103 | /** 104 | * {@inheritDoc} 105 | * 106 | * @see javax.sql.CommonDataSource#getLogWriter() 107 | */ 108 | @Override 109 | public final PrintWriter getLogWriter() throws SQLException { 110 | return DriverManager.getLogWriter(); 111 | } 112 | 113 | /** 114 | * {@inheritDoc} 115 | * 116 | * @see javax.sql.CommonDataSource#getLoginTimeout() 117 | */ 118 | @Override 119 | public final int getLoginTimeout() throws SQLException { 120 | return DriverManager.getLoginTimeout(); 121 | } 122 | 123 | /** 124 | * {@inheritDoc} 125 | * 126 | * @see javax.sql.CommonDataSource#setLogWriter(java.io.PrintWriter) 127 | */ 128 | @Override 129 | public final void setLogWriter(final PrintWriter out) throws SQLException { 130 | DriverManager.setLogWriter(out); 131 | } 132 | 133 | /** 134 | * {@inheritDoc} 135 | * 136 | * @see javax.sql.CommonDataSource#setLoginTimeout(int) 137 | */ 138 | @Override 139 | public final void setLoginTimeout(final int seconds) throws SQLException { 140 | DriverManager.setLoginTimeout(seconds); 141 | } 142 | 143 | /** 144 | * {@inheritDoc} 145 | * 146 | * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) 147 | */ 148 | @Override 149 | public final boolean isWrapperFor(final Class iface) throws SQLException { 150 | return DataSource.class.equals(iface); 151 | } 152 | 153 | /** 154 | * {@inheritDoc} 155 | * 156 | * @see java.sql.Wrapper#unwrap(java.lang.Class) 157 | */ 158 | @SuppressWarnings("unchecked") 159 | @Override 160 | public final T unwrap(final Class iface) throws SQLException { 161 | if (isWrapperFor(iface)) { 162 | return (T) this; 163 | } 164 | throw new SQLException("DriverManagerDataSource can only be unwrapped as javax.sql.DataSource, not as " 165 | + iface.getCanonicalName()); 166 | } 167 | 168 | /** 169 | * {@inheritDoc} 170 | * 171 | * @see javax.sql.DataSource#getConnection() 172 | */ 173 | @Override 174 | public final Connection getConnection() throws SQLException { 175 | if (needToRegisterDriver) { 176 | registerDriver(); 177 | } 178 | if (hasLength(jdbcUser) || jdbcPassword != null) { 179 | return getConnection(jdbcUser, jdbcPassword); 180 | } 181 | return DriverManager.getConnection(jdbcUrl); 182 | } 183 | 184 | /** 185 | * {@inheritDoc} 186 | * 187 | * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) 188 | */ 189 | @Override 190 | public final Connection getConnection(final String username, final String password) throws SQLException { 191 | if (needToRegisterDriver) { 192 | registerDriver(); 193 | } 194 | return DriverManager.getConnection(jdbcUrl, username, password); 195 | } 196 | 197 | /** 198 | * Register the JDBC driver. 199 | */ 200 | private void registerDriver() { 201 | for (final Enumeration drivers = DriverManager.getDrivers(); drivers.hasMoreElements();) { 202 | final Driver driver = drivers.nextElement(); 203 | if (driver.getClass().getCanonicalName().equals(jdbcDriver)) { 204 | needToRegisterDriver = false; 205 | return; 206 | } 207 | } 208 | try { 209 | final Class driverClass = Class.forName(jdbcDriver); 210 | if (!Driver.class.isAssignableFrom(driverClass)) { 211 | throw new RuntimeException("Driver " + driverClass + " does not implement " 212 | + Driver.class.getCanonicalName() + "!"); 213 | } 214 | needToRegisterDriver = false; 215 | } catch (final ClassNotFoundException e) { 216 | throw new RuntimeException("ClassNotFoundException attempting to load driver class " + jdbcDriver + "!", e); 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/derby/DerbyDataSourceRule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created May 5, 2011 8 | */ 9 | package junit.rules.derby; 10 | 11 | import java.io.PrintWriter; 12 | import java.sql.Connection; 13 | import java.sql.DriverManager; 14 | import java.sql.PreparedStatement; 15 | import java.sql.ResultSet; 16 | import java.sql.SQLException; 17 | import java.sql.Statement; 18 | 19 | import javax.sql.DataSource; 20 | 21 | import junit.rules.TestFixture; 22 | import junit.rules.jdbc.support.DriverManagerDataSource; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | /** 28 | * It's a JUnit {@link org.junit.Rule} that also masquerades as a JDBC {@link DataSource}. 29 | * 30 | * @author Alistair.Israel 31 | * @since 0.5 32 | */ 33 | public class DerbyDataSourceRule extends TestFixture implements DataSource { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(DerbyDataSourceRule.class); 36 | 37 | private final String databaseName; 38 | 39 | private DataSource dataSource; 40 | 41 | /** 42 | * Instantiates a new Derby DataSource rule. 43 | * 44 | * @param databaseName 45 | * the database name 46 | */ 47 | public DerbyDataSourceRule(final String databaseName) { 48 | this.databaseName = databaseName; 49 | } 50 | 51 | /** 52 | * Instantiates a new Derby DataSource rule with the default name ({@code "test"}). 53 | */ 54 | public DerbyDataSourceRule() { 55 | this("test"); 56 | } 57 | 58 | /** 59 | * Setup Derby 60 | * 61 | * @throws Throwable 62 | * if setup fails 63 | */ 64 | @Override 65 | protected final void setUp() throws Throwable { 66 | logger.debug("setUp()"); 67 | final String jdbcUrl = constructJdbcUrl(); 68 | logger.debug("Using JDBC URL: " + jdbcUrl); 69 | DriverManager.getConnection(jdbcUrl); 70 | 71 | final DriverManagerDataSource ds = new DriverManagerDataSource(); 72 | ds.setJdbcUrl(jdbcUrl); 73 | dataSource = ds; 74 | logger.info("Initialized Derby database at \"" + jdbcUrl + "\""); 75 | } 76 | 77 | /** 78 | * @return the JDBC URL to use 79 | */ 80 | private String constructJdbcUrl() { 81 | return "jdbc:derby:memory:" + databaseName + ";create=true"; 82 | } 83 | 84 | /** 85 | * {@inheritDoc} 86 | * 87 | * @see javax.sql.DataSource#getConnection() 88 | */ 89 | @Override 90 | public final Connection getConnection() throws SQLException { 91 | return dataSource.getConnection(); 92 | } 93 | 94 | /** 95 | * {@inheritDoc} 96 | * 97 | * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) 98 | */ 99 | @Override 100 | public final Connection getConnection(final String username, final String password) throws SQLException { 101 | return dataSource.getConnection(username, password); 102 | } 103 | 104 | /** 105 | * {@inheritDoc} 106 | * 107 | * @see javax.sql.CommonDataSource#getLogWriter() 108 | */ 109 | @Override 110 | public final PrintWriter getLogWriter() throws SQLException { 111 | return dataSource.getLogWriter(); 112 | } 113 | 114 | /** 115 | * {@inheritDoc} 116 | * 117 | * @see javax.sql.CommonDataSource#getLoginTimeout() 118 | */ 119 | @Override 120 | public final int getLoginTimeout() throws SQLException { 121 | return dataSource.getLoginTimeout(); 122 | } 123 | 124 | /** 125 | * {@inheritDoc} 126 | * 127 | * @see javax.sql.CommonDataSource#setLogWriter(java.io.PrintWriter) 128 | */ 129 | @Override 130 | public final void setLogWriter(final PrintWriter out) throws SQLException { 131 | dataSource.setLogWriter(out); 132 | } 133 | 134 | /** 135 | * {@inheritDoc} 136 | * 137 | * @see javax.sql.CommonDataSource#setLoginTimeout(int) 138 | */ 139 | @Override 140 | public final void setLoginTimeout(final int seconds) throws SQLException { 141 | dataSource.setLoginTimeout(seconds); 142 | } 143 | 144 | /** 145 | * {@inheritDoc} 146 | * 147 | * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) 148 | */ 149 | @Override 150 | public final boolean isWrapperFor(final Class iface) throws SQLException { 151 | return dataSource.isWrapperFor(iface); 152 | } 153 | 154 | /** 155 | * {@inheritDoc} 156 | * 157 | * @see java.sql.Wrapper#unwrap(java.lang.Class) 158 | */ 159 | @Override 160 | public final T unwrap(final Class iface) throws SQLException { 161 | return dataSource.unwrap(iface); 162 | } 163 | 164 | /** 165 | * @param sql 166 | * the SQL to execute 167 | * @return the number of rows affected 168 | * @since 0.5.1 169 | */ 170 | public final int execute(final String sql) { 171 | try { 172 | final Connection conn = dataSource.getConnection(); 173 | try { 174 | final Statement statement = conn.createStatement(); 175 | try { 176 | return statement.executeUpdate(sql); 177 | } finally { 178 | statement.close(); 179 | } 180 | } finally { 181 | conn.close(); 182 | } 183 | } catch (final SQLException e) { 184 | throw new AssertionError(e); 185 | } 186 | 187 | } 188 | 189 | /** 190 | * Don't know where else to put it for now. 191 | * 192 | * @param tableName 193 | * the table name to count 194 | * @return the count 195 | * @since 0.5.1 196 | */ 197 | public final int count(final String tableName) { 198 | try { 199 | final Connection conn = dataSource.getConnection(); 200 | try { 201 | final PreparedStatement ps = conn.prepareStatement("SELECT count(*) FROM " + tableName); 202 | try { 203 | final ResultSet rs = ps.executeQuery(); 204 | try { 205 | rs.next(); 206 | return rs.getInt(1); 207 | } finally { 208 | rs.close(); 209 | } 210 | } finally { 211 | ps.close(); 212 | } 213 | } finally { 214 | conn.close(); 215 | } 216 | } catch (final SQLException e) { 217 | throw new AssertionError(e); 218 | } 219 | } 220 | 221 | } 222 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/httpserver/SimpleHttpHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Sep 1, 2009 8 | */ 9 | package junit.rules.httpserver; 10 | 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.io.OutputStream; 15 | import java.io.PrintWriter; 16 | import java.net.HttpURLConnection; 17 | import java.net.URI; 18 | 19 | import com.sun.net.httpserver.Headers; 20 | import com.sun.net.httpserver.HttpExchange; 21 | import com.sun.net.httpserver.HttpHandler; 22 | 23 | /** 24 | *

25 | * Simplifies the effort to write an {@link HttpHandler}. 26 | *

27 | *

28 | * With contributions by Sam Tunnicliffe. 29 | *

30 | * 31 | * @author Alistair A. Israel 32 | */ 33 | public class SimpleHttpHandler implements HttpHandler { 34 | 35 | /** 36 | * {@value #GET} 37 | */ 38 | private static final String GET = "GET"; 39 | 40 | /** 41 | * {@value #POST} 42 | */ 43 | private static final String POST = "POST"; 44 | 45 | /** 46 | * {@value #PUT} 47 | */ 48 | private static final String PUT = "PUT"; 49 | 50 | /** 51 | * {@value #DELETE} 52 | */ 53 | private static final String DELETE = "DELETE"; 54 | 55 | /** 56 | * HTTP OK ({@value #HTTP_OK}) 57 | * 58 | * @see HttpURLConnection#HTTP_OK 59 | */ 60 | public static final int HTTP_OK = HttpURLConnection.HTTP_OK; 61 | 62 | private HttpExchange httpExchange; 63 | 64 | private ByteArrayOutputStream out; 65 | 66 | private PrintWriter pw; 67 | 68 | private int responseCodeSent; 69 | 70 | /** 71 | * {@inheritDoc} 72 | * 73 | * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange) 74 | */ 75 | @Override 76 | public final void handle(final HttpExchange exchange) throws IOException { 77 | this.httpExchange = exchange; 78 | this.out = new ByteArrayOutputStream(); 79 | this.pw = new PrintWriter(out); 80 | responseCodeSent = -1; 81 | final String requestMethod = exchange.getRequestMethod(); 82 | if (GET.equalsIgnoreCase(requestMethod)) { 83 | onGet(); 84 | } else if (POST.equalsIgnoreCase(requestMethod)) { 85 | onPost(); 86 | } else if (PUT.equalsIgnoreCase(requestMethod)) { 87 | onPut(); 88 | } else if (DELETE.equalsIgnoreCase(requestMethod)) { 89 | onDelete(); 90 | } 91 | if (responseCodeSent == -1) { 92 | sendResponse(HTTP_OK); 93 | } 94 | } 95 | 96 | /** 97 | * @return the httpExchange 98 | */ 99 | public final HttpExchange getHttpExchange() { 100 | return httpExchange; 101 | } 102 | 103 | /** 104 | * Get the request URI 105 | * 106 | * @return the request URI 107 | * @see com.sun.net.httpserver.HttpExchange#getRequestURI() 108 | */ 109 | protected final URI getRequestURI() { 110 | return httpExchange.getRequestURI(); 111 | } 112 | 113 | /** 114 | * Returns a stream from which the request body can be read. Multiple calls to this method will return the same 115 | * stream. It is recommended that applications should consume (read) all of the data from this stream before closing 116 | * it. If a stream is closed before all data has been read, then the close() call will read and discard remaining 117 | * data (up to an implementation specific number of bytes). 118 | * 119 | * @return the stream from which the request body can be read. 120 | * @see com.sun.net.httpserver.HttpExchange#getRequestBody() 121 | */ 122 | protected final InputStream getRequestBody() { 123 | return httpExchange.getRequestBody(); 124 | } 125 | 126 | /** 127 | * Returns an immutable Map containing the HTTP headers that were included with this request. The keys in this Map 128 | * will be the header names, while the values will be a List of Strings containing each value that was included 129 | * (either for a header that was listed several times, or one that accepts a comma-delimited list of values on a 130 | * single line). In either of these cases, the values for the header name will be presented in the order that they 131 | * were included in the request. 132 | * 133 | * @return a read-only Map which can be used to access request headers 134 | * @see com.sun.net.httpserver.HttpExchange#getRequestHeaders() 135 | */ 136 | protected final Headers getRequestHeaders() { 137 | return httpExchange.getRequestHeaders(); 138 | } 139 | 140 | /** 141 | * Get the request method 142 | * 143 | * @return the request method 144 | * @see com.sun.net.httpserver.HttpExchange#getRequestMethod() 145 | */ 146 | protected final String getRequestMethod() { 147 | return httpExchange.getRequestMethod(); 148 | } 149 | 150 | /** 151 | * Returns a {@link PrintWriter} to the response buffer used to calculate the byte length of the actual HTTP 152 | * response to be sent later. 153 | * 154 | * @return a {@link PrintWriter} 155 | */ 156 | protected final PrintWriter getResponseWriter() { 157 | return this.pw; 158 | } 159 | 160 | /** 161 | * Returns a mutable Map into which the HTTP response headers can be stored and which will be transmitted as part of 162 | * this response. The keys in the Map will be the header names, while the values must be a List of Strings 163 | * containing each value that should be included multiple times (in the order that they should be included). 164 | * 165 | * @return a writable Map which can be used to set response headers. 166 | * @see com.sun.net.httpserver.HttpExchange#getResponseHeaders() 167 | */ 168 | protected final Headers getResponseHeaders() { 169 | return httpExchange.getResponseHeaders(); 170 | } 171 | 172 | /** 173 | * @throws IOException 174 | * on exception 175 | */ 176 | protected void onGet() throws IOException { 177 | } 178 | 179 | /** 180 | * @throws IOException 181 | * on exception 182 | */ 183 | protected void onPost() throws IOException { 184 | } 185 | 186 | /** 187 | * @throws IOException 188 | * on exception 189 | */ 190 | protected void onPut() throws IOException { 191 | } 192 | 193 | /** 194 | * @throws IOException 195 | * on exception 196 | */ 197 | protected void onDelete() throws IOException { 198 | } 199 | 200 | /** 201 | * @param responseCode 202 | * the HTTP response code to send 203 | * @throws IOException 204 | * on exception 205 | */ 206 | protected final void sendResponse(final int responseCode) throws IOException { 207 | pw.flush(); 208 | httpExchange.sendResponseHeaders(responseCode, out.size()); 209 | final OutputStream responseBody = httpExchange.getResponseBody(); 210 | out.writeTo(responseBody); 211 | responseBody.flush(); 212 | httpExchange.close(); 213 | responseCodeSent = responseCode; 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jpa/hibernate/HibernatePersistenceContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 16, 2009 8 | */ 9 | package junit.rules.jpa.hibernate; 10 | 11 | import static junit.rules.util.Reflection.invoke; 12 | import static junit.rules.util.Reflection.set; 13 | 14 | import java.io.InputStream; 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.Method; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | import javax.annotation.PostConstruct; 21 | import javax.persistence.EntityManager; 22 | import javax.persistence.EntityManagerFactory; 23 | import javax.persistence.PersistenceContext; 24 | 25 | import junit.rules.TestFixture; 26 | import junit.rules.dbunit.Fixtures; 27 | import junit.rules.util.Reflection; 28 | 29 | import org.apache.derby.jdbc.EmbeddedDriver; 30 | import org.dbunit.JdbcDatabaseTester; 31 | import org.dbunit.dataset.CompositeDataSet; 32 | import org.dbunit.dataset.DataSetException; 33 | import org.dbunit.dataset.IDataSet; 34 | import org.dbunit.dataset.xml.XmlDataSet; 35 | import org.hibernate.ejb.Ejb3Configuration; 36 | import org.junit.runner.Description; 37 | import org.slf4j.Logger; 38 | import org.slf4j.LoggerFactory; 39 | 40 | /** 41 | * @author Alistair A. Israel 42 | * @since 0.3 43 | */ 44 | public class HibernatePersistenceContext extends TestFixture implements junit.rules.jpa.PersistenceContext { 45 | 46 | private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class); 47 | 48 | private final List fixtureNames = new ArrayList(); 49 | 50 | private EntityManagerFactory entityManagerFactory; 51 | 52 | private EntityManager entityManager; 53 | 54 | private JdbcDatabaseTester jdbcDatabaseTester; 55 | 56 | /** 57 | * @param classes 58 | * the annotated classes 59 | */ 60 | public HibernatePersistenceContext(final Class... classes) { 61 | final Ejb3Configuration cfg = DerbyHibernateUtil.configureDerbyHibernateJpa(classes); 62 | entityManagerFactory = cfg.buildEntityManagerFactory(); 63 | entityManager = entityManagerFactory.createEntityManager(); 64 | } 65 | 66 | /** 67 | * @param object 68 | * an object to which we will apply EJB 3.0 style @PersistenceContext and @PostConstruct handling 69 | */ 70 | @Override 71 | public final void injectAndPostConstruct(final Object object) { 72 | final Class clazz = object.getClass(); 73 | for (final Field field : clazz.getDeclaredFields()) { 74 | if (field.isAnnotationPresent(PersistenceContext.class)) { 75 | final Class type = field.getType(); 76 | if (type.equals(EntityManager.class)) { 77 | set(field).of(object).to(entityManager); 78 | } else { 79 | logger.warn("Found field \"{}\" annotated with @PersistenceContext but is of type {}", field 80 | .getName(), type.getName()); 81 | } 82 | } 83 | } 84 | 85 | for (final Method method : clazz.getDeclaredMethods()) { 86 | if (method.isAnnotationPresent(PostConstruct.class)) { 87 | final int nParameters = method.getParameterTypes().length; 88 | if (nParameters == 0) { 89 | invoke(method).on(object); 90 | } else { 91 | logger.warn("Found method \"{}\" annotated @PostConstruct " 92 | + "but don't know how to invoke with {} parameters", method.getName(), nParameters); 93 | } 94 | } 95 | } 96 | } 97 | 98 | /** 99 | * {@inheritDoc} 100 | * 101 | * @see junit.rules.TestFixture#inspect(org.junit.runner.Description) 102 | */ 103 | @Override 104 | protected final void inspect(final Description description) { 105 | final Class testClass = description.getTestClass(); 106 | if (testClass.isAnnotationPresent(Fixtures.class)) { 107 | addFixturesFromAnnotation(testClass.getAnnotation(Fixtures.class)); 108 | } 109 | final Method method = Reflection.quietlyGetMethod(testClass, description.getMethodName()); 110 | if (method.isAnnotationPresent(Fixtures.class)) { 111 | addFixturesFromAnnotation(method.getAnnotation(Fixtures.class)); 112 | } 113 | } 114 | 115 | /** 116 | * @param annotation 117 | * the {@link Fixtures} annotation 118 | */ 119 | private void addFixturesFromAnnotation(final Fixtures annotation) { 120 | for (final String fixtureName : annotation.value()) { 121 | fixtureNames.add(fixtureName); 122 | } 123 | } 124 | 125 | /** 126 | * {@inheritDoc} 127 | * 128 | * @see junit.rules.TestFixture#setUp() 129 | */ 130 | @Override 131 | protected final void setUp() throws Throwable { 132 | jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), DerbyHibernateUtil.JDBC_DERBY_URL); 133 | if (fixtureNames.isEmpty()) { 134 | logger.warn("No fixtures to load! Specify fixtures using @Fixtures."); 135 | } else { 136 | loadFixtures(); 137 | } 138 | 139 | jdbcDatabaseTester.onSetup(); 140 | } 141 | 142 | /** 143 | * @throws DataSetException 144 | * on any exception 145 | */ 146 | private void loadFixtures() throws DataSetException { 147 | final List dataSets = new ArrayList(); 148 | 149 | for (final String fixtureName : fixtureNames) { 150 | logger.trace("Attempting to load database fixture \"" + fixtureName + "\""); 151 | final IDataSet dataSet = attemptToLoadFixture(fixtureName); 152 | if (dataSet != null) { 153 | dataSets.add(dataSet); 154 | } 155 | } 156 | 157 | if (dataSets.isEmpty()) { 158 | logger.warn("Found 0 data sets!"); 159 | } else { 160 | final CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets.toArray(new IDataSet[dataSets 161 | .size()])); 162 | jdbcDatabaseTester.setDataSet(compositeDataSet); 163 | } 164 | } 165 | 166 | /** 167 | * @param fixtureName 168 | * the fixture name 169 | * @return {@link IDataSet} 170 | */ 171 | private IDataSet attemptToLoadFixture(final String fixtureName) { 172 | IDataSet dataSet = null; 173 | 174 | try { 175 | final InputStream in = ClassLoader.getSystemResourceAsStream(fixtureName); 176 | try { 177 | if (in != null) { 178 | if (fixtureName.endsWith(".xml")) { 179 | dataSet = new XmlDataSet(in); 180 | } 181 | } 182 | } finally { 183 | in.close(); 184 | } 185 | } catch (final Exception e) { 186 | logger.warn(e.getMessage(), e); 187 | } 188 | return dataSet; 189 | } 190 | 191 | /** 192 | * {@inheritDoc} 193 | * 194 | * @see junit.rules.TestFixture#tearDown() 195 | */ 196 | @Override 197 | protected final void tearDown() throws Throwable { 198 | jdbcDatabaseTester.onTearDown(); 199 | entityManagerFactory.close(); 200 | } 201 | 202 | /** 203 | * @return {@link EntityManager} 204 | * @see javax.persistence.EntityManagerFactory#createEntityManager() 205 | */ 206 | public final EntityManager getEntityManager() { 207 | return this.entityManager; 208 | } 209 | 210 | } 211 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | junit-rules 6 | junit-rules 7 | JUnit Rules Library 8 | 0.5.1 9 | 10 | 11 | 12 | MIT License 13 | LICENSE.txt 14 | 15 | 16 | 17 | 18 | 19 | UTF-8 20 | 21 | 22 | 23 | 24 | org.slf4j 25 | slf4j-log4j12 26 | 1.5.10 27 | test 28 | 29 | 30 | log4j 31 | log4j 32 | 33 | 34 | true 35 | 36 | 37 | log4j 38 | log4j 39 | 1.2.16 40 | jar 41 | test 42 | 43 | 44 | 45 | 46 | junit 47 | junit 48 | 4.9 49 | 50 | 51 | 52 | 53 | 54 | org.jboss.weld.se 55 | weld-se-core 56 | 1.1.0.Final 57 | true 58 | 59 | 60 | 61 | 62 | org.mortbay.jetty 63 | jetty 64 | 6.1.20 65 | provided 66 | true 67 | 68 | 69 | 70 | 71 | org.hibernate 72 | hibernate-core 73 | 3.3.2.GA 74 | compile 75 | 76 | 77 | slf4j-api 78 | org.slf4j 79 | 80 | 81 | true 82 | 83 | 84 | org.hibernate 85 | hibernate-entitymanager 86 | 3.4.0.GA 87 | compile 88 | 89 | 90 | slf4j-api 91 | org.slf4j 92 | 93 | 94 | true 95 | 96 | 97 | 98 | 99 | org.apache.derby 100 | derby 101 | 10.6.2.1 102 | compile 103 | true 104 | 105 | 106 | 107 | 108 | org.dbunit 109 | dbunit 110 | 2.4.8 111 | compile 112 | 113 | 114 | slf4j-api 115 | org.slf4j 116 | 117 | 118 | junit 119 | junit 120 | 121 | 122 | true 123 | 124 | 125 | 126 | 127 | 128 | org.slf4j 129 | slf4j-api 130 | 1.5.10 131 | compile 132 | 133 | 134 | 135 | 136 | 137 | javax.persistence 138 | persistence-api 139 | 1.0 140 | provided 141 | 142 | 143 | 144 | 145 | 146 | org.jboss.repositories.public-jboss 147 | http://repository.jboss.org/nexus/content/groups/public-jboss 148 | 149 | true 150 | 151 | 152 | false 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-compiler-plugin 163 | 2.3.2 164 | 165 | 1.6 166 | 1.6 167 | 168 | 169 | 170 | 171 | 172 | org.apache.maven.plugins 173 | maven-checkstyle-plugin 174 | 2.6 175 | 176 | ${basedir}/etc/checkstyle.xml 177 | config_loc=${project.basedir}/etc 178 | true 179 | true 180 | UTF-8 181 | 182 | 183 | 184 | test 185 | 186 | check 187 | 188 | 189 | true 190 | warning 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | org.apache.maven.plugins 199 | maven-source-plugin 200 | 2.1.2 201 | 202 | 203 | attach-sources 204 | verify 205 | 206 | jar 207 | 208 | 209 | 210 | 211 | 212 | 213 | org.apache.maven.plugins 214 | maven-surefire-plugin 215 | 2.7.1 216 | 217 | 218 | 219 | derby.system.home 220 | ${project.build.directory} 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | org.apache.maven.plugins 234 | maven-javadoc-plugin 235 | 2.7 236 | 237 | 238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/util/Reflection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Oct 15, 2009 8 | */ 9 | package junit.rules.util; 10 | 11 | import java.lang.reflect.Field; 12 | import java.lang.reflect.InvocationTargetException; 13 | import java.lang.reflect.Method; 14 | import java.util.Iterator; 15 | 16 | /** 17 | *

18 | * Provides a set of utility methods (and classes) for reflection. 19 | *

20 | *

21 | * Basically, a clever way to be able to write: 22 | *

23 | * 24 | *
 25 |  * Reflection.set(field).of(target).to(value);
 26 |  * 
27 | * 28 | * @author Alistair A. Israel 29 | * @since 0.3.1 30 | */ 31 | public final class Reflection { 32 | 33 | /** 34 | * Utility classes should not have a public or default constructor. 35 | */ 36 | private Reflection() { 37 | // noop 38 | } 39 | 40 | /** 41 | * @param field 42 | * the Field to set 43 | * @return {@link FieldWrapper} 44 | */ 45 | public static FieldWrapper set(final Field field) { 46 | return new FieldWrapper(field); 47 | } 48 | 49 | /** 50 | *

51 | * Lets us write ReflectionUtils.set(field). 52 | *

53 | */ 54 | public static class FieldWrapper { 55 | 56 | private final Field field; 57 | 58 | /** 59 | * @param field 60 | * {@link Field} 61 | */ 62 | public FieldWrapper(final Field field) { 63 | this.field = field; 64 | } 65 | 66 | /** 67 | * @param target 68 | * the object whose field we're setting 69 | * @return Setter 70 | */ 71 | public final Setter of(final Object target) { 72 | return new Setter(target); 73 | } 74 | 75 | /** 76 | *

77 | * Lets us write ReflectionUtils.set(field).of(target). 78 | *

79 | */ 80 | public class Setter { 81 | 82 | private final Object target; 83 | 84 | /** 85 | * @param target 86 | * the object to set the field value for 87 | */ 88 | public Setter(final Object target) { 89 | this.target = target; 90 | } 91 | 92 | /** 93 | *

94 | * Let's us write ReflectionUtils.set(field).of(target).to(value) . 95 | *

96 | * 97 | * @param value 98 | * the value to set the field to 99 | */ 100 | public final void to(final Object value) { 101 | quietlySetField(field, target, value); 102 | } 103 | } 104 | } 105 | 106 | /** 107 | * @param field 108 | * the field to set 109 | * @param target 110 | * the object whose field we're setting 111 | * @param value 112 | * the value to set it to 113 | */ 114 | public static void quietlySetField(final Field field, final Object target, final Object value) { 115 | try { 116 | final boolean accessible = field.isAccessible(); 117 | if (!accessible) { 118 | field.setAccessible(true); 119 | } 120 | field.set(target, value); 121 | if (!accessible) { 122 | field.setAccessible(false); 123 | } 124 | } catch (final IllegalAccessException e) { 125 | throw new RuntimeException(e.getMessage(), e); 126 | } 127 | } 128 | 129 | /** 130 | *

131 | * Allows us to cleverly write: 132 | *

133 | * 134 | *
135 |      * Reflection.invoke(method).on(object);
136 |      * 
137 | * 138 | * @author Alistair A. Israel 139 | * @since 0.3.1 140 | */ 141 | public static class MethodInvoker { 142 | 143 | private final Method method; 144 | 145 | /** 146 | * @param method 147 | * the method to invoke 148 | */ 149 | public MethodInvoker(final Method method) { 150 | this.method = method; 151 | } 152 | 153 | /** 154 | * @param object 155 | * the ojbect to invoke the method on 156 | * @param params 157 | * any parameters to the method invocation 158 | * @return any return value 159 | */ 160 | public final Object on(final Object object, final Object... params) { 161 | return quietlyInvokeMethod(object, method, params); 162 | } 163 | } 164 | 165 | /** 166 | * @param method 167 | * the method to invoke 168 | * @return {@link MethodInvoker} 169 | */ 170 | public static MethodInvoker invoke(final Method method) { 171 | return new MethodInvoker(method); 172 | } 173 | 174 | 175 | /** 176 | * @param clazz 177 | * the {@link Class} 178 | * @param methodName 179 | * the name of the method we're interested in 180 | * @param parameterTypes 181 | * the parameter types 182 | * @return the {@link Method} found, or {@code null} if no matching method is found 183 | * @since 0.5.1 184 | */ 185 | public static Method quietlyGetMethod(final Class clazz, final String methodName, 186 | final Class... parameterTypes) { 187 | try { 188 | return clazz.getMethod(methodName, parameterTypes); 189 | } catch (final SecurityException e) { 190 | throw new RuntimeException("SecurityException attempting to retrieve method \"" + methodName 191 | + "\" from class " + clazz.getName(), e); 192 | } catch (final NoSuchMethodException e) { 193 | return null; 194 | } 195 | } 196 | 197 | /** 198 | * @param object 199 | * the object to invoke the method on 200 | * @param method 201 | * the method to invoke 202 | * @param params 203 | * any parameters to the method 204 | * @return any return value 205 | */ 206 | public static Object quietlyInvokeMethod(final Object object, final Method method, final Object... params) { 207 | try { 208 | final boolean accessible = method.isAccessible(); 209 | if (!accessible) { 210 | method.setAccessible(true); 211 | } 212 | try { 213 | return method.invoke(object, params); 214 | } finally { 215 | if (!accessible) { 216 | method.setAccessible(false); 217 | } 218 | } 219 | } catch (final IllegalArgumentException e) { 220 | throw new RuntimeException(e.getMessage(), e); 221 | } catch (final IllegalAccessException e) { 222 | throw new RuntimeException(e.getMessage(), e); 223 | } catch (final InvocationTargetException e) { 224 | throw new RuntimeException(e.getMessage(), e); 225 | } 226 | } 227 | 228 | /** 229 | * @param clazz 230 | * the class 231 | * @return an iterable for the class hierarchy 232 | */ 233 | public static Iterable> iterateClassHierarchy(final Class clazz) { 234 | return new Iterable>() { 235 | @Override 236 | public Iterator> iterator() { 237 | return new ReadOnlyIterator>() { 238 | 239 | private Class cl = clazz; 240 | 241 | @Override 242 | public boolean hasNext() { 243 | return cl != null && cl != Class.class; 244 | } 245 | 246 | @Override 247 | public Class next() { 248 | final Class next = cl; 249 | cl = cl.getSuperclass(); 250 | return next; 251 | } 252 | }; 253 | } 254 | }; 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/junit/rules/jndi/StubJndiContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * junit-rules: JUnit Rules Library 3 | * 4 | * Copyright (c) 2009-2011 by Alistair A. Israel. 5 | * This software is made available under the terms of the MIT License. 6 | * 7 | * Created Jun 2, 2011 8 | */ 9 | package junit.rules.jndi; 10 | 11 | import java.util.HashMap; 12 | import java.util.Hashtable; 13 | import java.util.Map; 14 | import java.util.Map.Entry; 15 | import java.util.logging.Logger; 16 | 17 | import javax.naming.Binding; 18 | import javax.naming.Context; 19 | import javax.naming.Name; 20 | import javax.naming.NameClassPair; 21 | import javax.naming.NameParser; 22 | import javax.naming.NamingEnumeration; 23 | import javax.naming.NamingException; 24 | import javax.naming.spi.InitialContextFactory; 25 | import javax.naming.spi.InitialContextFactoryBuilder; 26 | import javax.naming.spi.NamingManager; 27 | 28 | import junit.rules.TestFixture; 29 | 30 | /** 31 | * A 'stub' JNDI Context backed by a simple {@link Map}, useful only for unit testing. This implementation is 32 | * not thread-safe, and should not be used in production. Consider using Spring's SimpleNamingContext 33 | * for a more robust implementation with more features. 34 | * 35 | * @author Alistair.Israel 36 | */ 37 | public class StubJndiContext extends TestFixture { 38 | 39 | private static final Logger logger = Logger.getLogger(StubJndiContext.class.getCanonicalName()); 40 | 41 | private final Map boundObjects = new HashMap(); 42 | 43 | private boolean closed; 44 | 45 | /** 46 | * The {@link InitialContextFactoryBuilder} for our {@link StubContext} 47 | * 48 | * @author Alistair A. Israel 49 | */ 50 | private class StubContextFactoryBuilder implements InitialContextFactoryBuilder { 51 | 52 | /** 53 | * {@inheritDoc} 54 | * 55 | * @see javax.naming.spi.InitialContextFactoryBuilder#createInitialContextFactory(java.util.Hashtable) 56 | */ 57 | @Override 58 | public InitialContextFactory createInitialContextFactory(final Hashtable environment) 59 | throws NamingException { 60 | return new InitialContextFactory() { 61 | @Override 62 | public Context getInitialContext(final Hashtable environment) throws NamingException { 63 | return new StubContext(environment); 64 | } 65 | }; 66 | } 67 | } 68 | 69 | /** 70 | * @param name 71 | * the name to bind to 72 | * @param obj 73 | * the object to bind 74 | */ 75 | public final void bind(final String name, final Object obj) { 76 | boundObjects.put(name, obj); 77 | logger.finest("Bound " + obj.getClass().getCanonicalName() + "@" + System.identityHashCode(obj) + " to \"" 78 | + name + "\""); 79 | } 80 | 81 | /** 82 | * {@inheritDoc} 83 | * 84 | * @see junit.rules.TestFixture#setUp() 85 | */ 86 | @Override 87 | protected final void setUp() throws Throwable { 88 | logger.info("Activating stub JNDI context"); 89 | if (!NamingManager.hasInitialContextFactoryBuilder()) { 90 | try { 91 | NamingManager.setInitialContextFactoryBuilder(new StubContextFactoryBuilder()); 92 | } catch (final NamingException e) { 93 | throw new RuntimeException(e.getClass().getCanonicalName() 94 | + " attempting to activate StubJndiContextBuilder", e); 95 | } 96 | } 97 | } 98 | 99 | /** 100 | * @return if {@link StubContext#close()} was called 101 | */ 102 | public final boolean wasClosed() { 103 | return closed; 104 | } 105 | 106 | /** 107 | * Our internal, stub JNDI context. 108 | */ 109 | private class StubContext implements Context { 110 | 111 | private final Hashtable environment; 112 | 113 | /** 114 | * @param environment 115 | * this context's environment 116 | */ 117 | public StubContext(final Hashtable environment) { 118 | this.environment = new Hashtable(); 119 | if (environment != null && !environment.isEmpty()) { 120 | for (final Entry entry : environment.entrySet()) { 121 | this.environment.put(entry.getKey().toString(), entry.getValue()); 122 | } 123 | } 124 | } 125 | 126 | /** 127 | * {@inheritDoc} 128 | * 129 | * @see javax.naming.Context#addToEnvironment(java.lang.String, java.lang.Object) 130 | */ 131 | @Override 132 | public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { 133 | return environment.put(propName, propVal); 134 | } 135 | 136 | /** 137 | * {@inheritDoc} 138 | * 139 | * @see javax.naming.Context#bind(java.lang.String, java.lang.Object) 140 | */ 141 | @Override 142 | public void bind(final String name, final Object obj) throws NamingException { 143 | boundObjects.put(name, obj); 144 | logger.finest("Bound \"" + name + "\" to " + obj.getClass().getCanonicalName() + "@" 145 | + System.identityHashCode(obj)); 146 | } 147 | 148 | /** 149 | * {@inheritDoc} 150 | * 151 | * @see javax.naming.Context#close() 152 | */ 153 | @Override 154 | public void close() throws NamingException { 155 | closed = true; 156 | } 157 | 158 | /** 159 | * {@inheritDoc} 160 | * 161 | * @see javax.naming.Context#composeName(java.lang.String, java.lang.String) 162 | */ 163 | @Override 164 | public String composeName(final String name, final String prefix) throws NamingException { 165 | return prefix + name; 166 | } 167 | 168 | /** 169 | * {@inheritDoc} 170 | * 171 | * @see javax.naming.Context#createSubcontext(java.lang.String) 172 | */ 173 | @Override 174 | public Context createSubcontext(final String name) throws NamingException { 175 | throw notSupported(); 176 | } 177 | 178 | /** 179 | * {@inheritDoc} 180 | * 181 | * @see javax.naming.Context#destroySubcontext(java.lang.String) 182 | */ 183 | @Override 184 | public void destroySubcontext(final String name) throws NamingException { 185 | // TODO Auto-generated method stub 186 | 187 | } 188 | 189 | /** 190 | * {@inheritDoc} 191 | * 192 | * @see javax.naming.Context#getEnvironment() 193 | */ 194 | @Override 195 | public Hashtable getEnvironment() throws NamingException { 196 | return this.environment; 197 | } 198 | 199 | /** 200 | * {@inheritDoc} 201 | * 202 | * @see javax.naming.Context#list(java.lang.String) 203 | */ 204 | @Override 205 | public NamingEnumeration list(final String name) throws NamingException { 206 | // TODO Auto-generated method stub 207 | return null; 208 | } 209 | 210 | /** 211 | * {@inheritDoc} 212 | * 213 | * @see javax.naming.Context#listBindings(java.lang.String) 214 | */ 215 | @Override 216 | public NamingEnumeration listBindings(final String name) throws NamingException { 217 | throw notSupported(); 218 | } 219 | 220 | /** 221 | * {@inheritDoc} 222 | * 223 | * @see javax.naming.Context#lookup(java.lang.String) 224 | */ 225 | @Override 226 | public Object lookup(final String name) throws NamingException { 227 | final Object o = boundObjects.get(name); 228 | if (o != null) { 229 | logger.finest("lookup(\"" + name + "\") returning " + o.getClass().getCanonicalName() + "@" 230 | + System.identityHashCode(o)); 231 | } else { 232 | logger.finest("lookup(\"" + name + "\") returning null"); 233 | } 234 | return o; 235 | } 236 | 237 | /** 238 | * {@inheritDoc} 239 | * 240 | * @see javax.naming.Context#lookupLink(java.lang.String) 241 | */ 242 | @Override 243 | public Object lookupLink(final String name) throws NamingException { 244 | throw notSupported(); 245 | } 246 | 247 | /** 248 | * {@inheritDoc} 249 | * 250 | * @see javax.naming.Context#rebind(java.lang.String, java.lang.Object) 251 | */ 252 | @Override 253 | public void rebind(final String name, final Object obj) throws NamingException { 254 | boundObjects.put(name, obj); 255 | } 256 | 257 | /** 258 | * {@inheritDoc} 259 | * 260 | * @see javax.naming.Context#removeFromEnvironment(java.lang.String) 261 | */ 262 | @Override 263 | public Object removeFromEnvironment(final String propName) throws NamingException { 264 | return environment.remove(propName); 265 | } 266 | 267 | /** 268 | * {@inheritDoc} 269 | * 270 | * @see javax.naming.Context#rename(java.lang.String, java.lang.String) 271 | */ 272 | @Override 273 | public void rename(final String oldName, final String newName) throws NamingException { 274 | if (!boundObjects.containsKey(oldName)) { 275 | throw new NamingException("StubJndiContext namme \"" + oldName + "\" not bound!"); 276 | } 277 | if (boundObjects.containsKey(newName)) { 278 | throw new NamingException("StubJndiContext name \"" + oldName + "\" already bound to object of type: " 279 | + boundObjects.get(newName).getClass().getCanonicalName()); 280 | } 281 | 282 | final Object obj = boundObjects.remove(oldName); 283 | boundObjects.put(newName, obj); 284 | } 285 | 286 | /** 287 | * {@inheritDoc} 288 | * 289 | * @see javax.naming.Context#unbind(java.lang.String) 290 | */ 291 | @Override 292 | public void unbind(final String name) throws NamingException { 293 | throw notSupported(); 294 | } 295 | 296 | /** 297 | * {@inheritDoc} 298 | * 299 | * @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object) 300 | */ 301 | @Override 302 | public void bind(final Name name, final Object obj) throws NamingException { 303 | throw notSupported(); 304 | } 305 | 306 | /** 307 | * {@inheritDoc} 308 | * 309 | * @see javax.naming.Context#composeName(javax.naming.Name, javax.naming.Name) 310 | */ 311 | @Override 312 | public Name composeName(final Name name, final Name prefix) throws NamingException { 313 | throw notSupported(); 314 | } 315 | 316 | /** 317 | * {@inheritDoc} 318 | * 319 | * @see javax.naming.Context#createSubcontext(javax.naming.Name) 320 | */ 321 | @Override 322 | public Context createSubcontext(final Name name) throws NamingException { 323 | throw notSupported(); 324 | } 325 | 326 | /** 327 | * {@inheritDoc} 328 | * 329 | * @see javax.naming.Context#destroySubcontext(javax.naming.Name) 330 | */ 331 | @Override 332 | public void destroySubcontext(final Name name) throws NamingException { 333 | throw notSupported(); 334 | } 335 | 336 | /** 337 | * {@inheritDoc} 338 | * 339 | * @see javax.naming.Context#getNameInNamespace() 340 | */ 341 | @Override 342 | public String getNameInNamespace() throws NamingException { 343 | throw notSupported(); 344 | } 345 | 346 | /** 347 | * {@inheritDoc} 348 | * 349 | * @see javax.naming.Context#getNameParser(javax.naming.Name) 350 | */ 351 | @Override 352 | public NameParser getNameParser(final Name name) throws NamingException { 353 | throw notSupported(); 354 | } 355 | 356 | /** 357 | * {@inheritDoc} 358 | * 359 | * @see javax.naming.Context#getNameParser(java.lang.String) 360 | */ 361 | @Override 362 | public NameParser getNameParser(final String name) throws NamingException { 363 | throw notSupported(); 364 | } 365 | 366 | /** 367 | * {@inheritDoc} 368 | * 369 | * @see javax.naming.Context#list(javax.naming.Name) 370 | */ 371 | @Override 372 | public NamingEnumeration list(final Name name) throws NamingException { 373 | throw notSupported(); 374 | } 375 | 376 | /** 377 | * {@inheritDoc} 378 | * 379 | * @see javax.naming.Context#listBindings(javax.naming.Name) 380 | */ 381 | @Override 382 | public NamingEnumeration listBindings(final Name name) throws NamingException { 383 | throw notSupported(); 384 | } 385 | 386 | /** 387 | * {@inheritDoc} 388 | * 389 | * @see javax.naming.Context#lookup(javax.naming.Name) 390 | */ 391 | @Override 392 | public Object lookup(final Name name) throws NamingException { 393 | throw notSupported(); 394 | } 395 | 396 | /** 397 | * {@inheritDoc} 398 | * 399 | * @see javax.naming.Context#lookupLink(javax.naming.Name) 400 | */ 401 | @Override 402 | public Object lookupLink(final Name name) throws NamingException { 403 | throw notSupported(); 404 | } 405 | 406 | /** 407 | * {@inheritDoc} 408 | * 409 | * @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object) 410 | */ 411 | @Override 412 | public void rebind(final Name name, final Object obj) throws NamingException { 413 | throw notSupported(); 414 | } 415 | 416 | /** 417 | * {@inheritDoc} 418 | * 419 | * @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name) 420 | */ 421 | @Override 422 | public void rename(final Name oldName, final Name newName) throws NamingException { 423 | throw notSupported(); 424 | } 425 | 426 | /** 427 | * {@inheritDoc} 428 | * 429 | * @see javax.naming.Context#unbind(javax.naming.Name) 430 | */ 431 | @Override 432 | public void unbind(final Name name) throws NamingException { 433 | throw notSupported(); 434 | } 435 | 436 | } 437 | 438 | /** 439 | * Equivalent to: 440 | * 441 | *
442 |      * new UnsupportedOperationException("ClassName.MethodName is not supported!");
443 |      * 
444 | * 445 | * @return {@link UnsupportedOperationException} 446 | */ 447 | public static UnsupportedOperationException notSupported() { 448 | final StackTraceElement[] unwound = unwindStackTrace(Thread.currentThread().getStackTrace()); 449 | final UnsupportedOperationException e = new UnsupportedOperationException("StubJndiContext." 450 | + unwound[0].getMethodName() + " is not supported!"); 451 | e.setStackTrace(unwound); 452 | return e; 453 | } 454 | 455 | /** 456 | * @param st 457 | * the {@link StackTraceElement}[] 458 | * @return the remaining {@link StackTraceElement}[] 459 | */ 460 | private static StackTraceElement[] unwindStackTrace(final StackTraceElement[] st) { 461 | final int len = st.length; 462 | 463 | int i = 0; 464 | // Unwind up to StubJndiContext 465 | final String stubJndiContext = StubJndiContext.class.getName(); 466 | while (i < len && !st[i].getClassName().equals(stubJndiContext)) { 467 | ++i; 468 | } 469 | // Unwind past unwindStackTrace() and notSupported() 470 | i += 2; 471 | 472 | final int rest = len - i; 473 | final StackTraceElement[] unwound = new StackTraceElement[rest]; 474 | System.arraycopy(st, i, unwound, 0, rest); 475 | return unwound; 476 | } 477 | } 478 | --------------------------------------------------------------------------------