001 /* 002 * SonarQube, open source software quality management tool. 003 * Copyright (C) 2008-2014 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * SonarQube is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * SonarQube is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020 package org.sonar.test; 021 022 import org.apache.commons.io.FileUtils; 023 import org.apache.commons.lang.StringUtils; 024 025 import java.io.File; 026 import java.lang.reflect.Constructor; 027 import java.lang.reflect.Modifier; 028 import java.net.URL; 029 030 import static org.fest.assertions.Assertions.assertThat; 031 import static org.fest.assertions.Fail.fail; 032 033 /** 034 * Utilities for unit tests 035 * 036 * @since 2.2 037 */ 038 public final class TestUtils { 039 040 private TestUtils() { 041 } 042 043 /** 044 * Search for a test resource in the classpath. For example getResource("org/sonar/MyClass/foo.txt"); 045 * 046 * @param path the starting slash is optional 047 * @return the resource. Null if resource not found 048 */ 049 public static File getResource(String path) { 050 String resourcePath = path; 051 if (!resourcePath.startsWith("/")) { 052 resourcePath = "/" + resourcePath; 053 } 054 URL url = TestUtils.class.getResource(resourcePath); 055 if (url != null) { 056 return FileUtils.toFile(url); 057 } 058 return null; 059 } 060 061 /** 062 * Search for a resource in the classpath. For example calling the method getResource(getClass(), "myTestName/foo.txt") from 063 * the class org.sonar.Foo loads the file $basedir/src/test/resources/org/sonar/Foo/myTestName/foo.txt 064 * 065 * @return the resource. Null if resource not found 066 */ 067 public static File getResource(Class baseClass, String path) { 068 String resourcePath = StringUtils.replaceChars(baseClass.getCanonicalName(), '.', '/'); 069 if (!path.startsWith("/")) { 070 resourcePath += "/"; 071 } 072 resourcePath += path; 073 return getResource(resourcePath); 074 } 075 076 public static void assertPrivateConstructor(Class clazz) { 077 try { 078 Constructor constructor = clazz.getDeclaredConstructor(); 079 assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); 080 constructor.setAccessible(true); 081 constructor.newInstance(); 082 } catch (Exception e) { 083 fail("Fail to instantiate " + clazz, e); 084 } 085 } 086 }