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.net.URL;
027
028 /**
029 * Utilities for unit tests
030 *
031 * @since 2.2
032 */
033 public final class TestUtils {
034
035 private TestUtils() {
036 }
037
038 /**
039 * Search for a test resource in the classpath. For example getResource("org/sonar/MyClass/foo.txt");
040 *
041 * @param path the starting slash is optional
042 * @return the resource. Null if resource not found
043 */
044 public static File getResource(String path) {
045 String resourcePath = path;
046 if (!resourcePath.startsWith("/")) {
047 resourcePath = "/" + resourcePath;
048 }
049 URL url = TestUtils.class.getResource(resourcePath);
050 if (url != null) {
051 return FileUtils.toFile(url);
052 }
053 return null;
054 }
055
056 /**
057 * Search for a resource in the classpath. For example calling the method getResource(getClass(), "myTestName/foo.txt") from
058 * the class org.sonar.Foo loads the file $basedir/src/test/resources/org/sonar/Foo/myTestName/foo.txt
059 *
060 * @return the resource. Null if resource not found
061 */
062 public static File getResource(Class baseClass, String path) {
063 String resourcePath = StringUtils.replaceChars(baseClass.getCanonicalName(), '.', '/');
064 if (!path.startsWith("/")) {
065 resourcePath += "/";
066 }
067 resourcePath += path;
068 return getResource(resourcePath);
069 }
070 }