001/** 002 * Copyright 2005-2014 The Kuali Foundation 003 * 004 * Licensed under the Educational Community License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.opensource.org/licenses/ecl2.php 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.kuali.rice.test.runners; 017 018import org.apache.commons.beanutils.MethodUtils; 019import org.junit.runner.notification.RunNotifier; 020import org.junit.runners.BlockJUnit4ClassRunner; 021import org.junit.runners.model.FrameworkMethod; 022import org.junit.runners.model.InitializationError; 023import org.kuali.rice.test.MethodAware; 024 025import java.lang.reflect.Method; 026 027/** 028 * A Runner which sets up Rice unit tests appropriately. 029 * 1) It invokes setName() on the Test (if the method exists) and sets it to the name of the test method being invoked. 030 * 031 * @author Kuali Rice Team (rice.collab@kuali.org) 032 * @since 0.9 033 */ 034public class RiceUnitTestClassRunner extends BlockJUnit4ClassRunner { 035 private Method currentMethod; 036 037 public RiceUnitTestClassRunner(final Class<?> testClass) throws InitializationError { 038 super(testClass); 039 040 } 041 042 @Override 043 protected void runChild(FrameworkMethod method, RunNotifier runNotifier) { 044 this.currentMethod = method.getMethod(); 045 try { 046 super.runChild(method, runNotifier); 047 } finally { 048 this.currentMethod = null; 049 } 050 } 051 052 @Override 053 protected Object createTest() throws Exception { 054 Object test = super.createTest(); 055 setTestName(test, currentMethod); 056 setTestMethod(test, currentMethod); 057 return test; 058 } 059 060 /** 061 * Sets the {@link java.lang.reflect.Method} on the test case if it is {@link MethodAware} 062 * @param method the current method to be run 063 * @param test the test instance 064 */ 065 protected void setTestMethod(Object test, Method method) { 066 if (test instanceof MethodAware) { 067 ((MethodAware) test).setTestMethod(method); 068 } 069 } 070 071 protected void setTestName(final Object test, final Method testMethod) throws Exception { 072 String name = testMethod == null ? "" : testMethod.getName(); 073 final Method setNameMethod = MethodUtils.getAccessibleMethod(test.getClass(), "setName", new Class[]{String.class}); 074 if (setNameMethod != null) { 075 setNameMethod.invoke(test, name); 076 } 077 } 078 079}