001/** 002 * Copyright (C) 2006-2023 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 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.talend.sdk.component.junit.delegate; 017 018import static java.util.Optional.ofNullable; 019import static lombok.AccessLevel.PROTECTED; 020 021import java.lang.reflect.InvocationTargetException; 022import java.util.Optional; 023 024import org.junit.runner.Description; 025import org.junit.runner.Runner; 026import org.junit.runner.notification.RunNotifier; 027import org.junit.runners.JUnit4; 028import org.junit.runners.model.InitializationError; 029 030import lombok.Getter; 031 032public class DelegatingRunner extends Runner { 033 034 private final Runner delegate; 035 036 @Getter(PROTECTED) 037 private final Class<?> testClass; 038 039 public DelegatingRunner(final Class<?> testClass) throws InitializationError { 040 this.testClass = testClass; 041 try { 042 final Optional<? extends Class<? extends Runner>> delegateClass = 043 ofNullable(testClass.getAnnotation(DelegateRunWith.class)).map(DelegateRunWith::value); 044 this.delegate = 045 delegateClass.isPresent() ? delegateClass.get().getConstructor(Class.class).newInstance(testClass) 046 : new JUnit4(testClass); 047 } catch (final InstantiationException | NoSuchMethodException | IllegalAccessException e) { 048 throw new IllegalArgumentException(e); 049 } catch (final InvocationTargetException e) { 050 if (InitializationError.class.isInstance(e.getCause())) { 051 throw InitializationError.class.cast(e.getCause()); 052 } 053 throw new IllegalStateException(e.getTargetException()); 054 } 055 } 056 057 @Override 058 public Description getDescription() { 059 return delegate.getDescription(); 060 } 061 062 @Override 063 public void run(final RunNotifier notifier) { 064 delegate.run(notifier); 065 } 066}