001/* 002 * Copyright 2011 Atteo. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014package org.atteo.moonshine.tests; 015 016import java.util.HashMap; 017import java.util.concurrent.Callable; 018 019import org.junit.rules.TestRule; 020import org.junit.runner.Description; 021import org.junit.runners.model.Statement; 022 023import com.google.inject.Key; 024import com.google.inject.servlet.ServletScopes; 025 026/** 027 * With this rule added the test acts as if it were executed as a part of a HTTP request. 028 * 029 * <p> 030 * The test methods of the JUnit test will be executed 031 * in {@link ServletScopes#REQUEST REQUEST} scope 032 * using {@link ServletScopes#scopeRequest(java.util.concurrent.Callable, java.util.Map)}. 033 * </p> 034 */ 035public class RequestRule implements TestRule { 036 @Override 037 public Statement apply(final Statement base, Description method) { 038 return new Statement() { 039 @Override 040 public void evaluate() throws Throwable { 041 ServletScopes.scopeRequest(new Callable<Object>() { 042 @Override 043 public Object call() throws Exception { 044 try { 045 base.evaluate(); 046 } catch (RuntimeException | Error e) { 047 // don't wrap RuntimeExceptions 048 // don't wrap Errors either, JUnit throws this 049 throw e; 050 } catch (Throwable e) { 051 throw new RuntimeException(e); 052 } 053 return null; 054 } 055 056 }, new HashMap<Key<?>, Object>()).call(); 057 } 058 }; 059 } 060}