Search in sources :

Example 1 with RunWith

use of org.junit.runner.RunWith in project intellij-community by JetBrains.

the class JUnit4TestRunnerUtil method buildRequest.

public static Request buildRequest(String[] suiteClassNames, final String name, boolean notForked) {
    if (suiteClassNames.length == 0) {
        return null;
    }
    Vector result = new Vector();
    for (int i = 0; i < suiteClassNames.length; i++) {
        String suiteClassName = suiteClassNames[i];
        if (suiteClassName.charAt(0) == '@') {
            // all tests in the package specified
            try {
                final Map classMethods = new HashMap();
                BufferedReader reader = new BufferedReader(new FileReader(suiteClassName.substring(1)));
                try {
                    final String packageName = reader.readLine();
                    if (packageName == null)
                        return null;
                    final String categoryName = reader.readLine();
                    final Class category = categoryName != null && categoryName.length() > 0 ? loadTestClass(categoryName) : null;
                    String line;
                    while ((line = reader.readLine()) != null) {
                        String className = line;
                        final int idx = line.indexOf(',');
                        if (idx != -1) {
                            className = line.substring(0, idx);
                            Set methodNames = (Set) classMethods.get(className);
                            if (methodNames == null) {
                                methodNames = new HashSet();
                                classMethods.put(className, methodNames);
                            }
                            methodNames.add(line.substring(idx + 1));
                        }
                        appendTestClass(result, className);
                    }
                    String suiteName = packageName.length() == 0 ? "<default package>" : packageName;
                    Class[] classes = getArrayOfClasses(result);
                    if (classes.length == 0) {
                        System.out.println(TestRunnerUtil.testsFoundInPackageMesage(0, suiteName));
                        return null;
                    }
                    Request allClasses;
                    try {
                        Class.forName("org.junit.runner.Computer");
                        allClasses = JUnit46ClassesRequestBuilder.getClassesRequest(suiteName, classes, classMethods, category);
                    } catch (ClassNotFoundException e) {
                        allClasses = getClassRequestsUsing44API(suiteName, classes);
                    } catch (NoSuchMethodError e) {
                        allClasses = getClassRequestsUsing44API(suiteName, classes);
                    }
                    return classMethods.isEmpty() ? allClasses : allClasses.filterWith(new Filter() {

                        public boolean shouldRun(Description description) {
                            if (description.isTest()) {
                                final Set methods = (Set) classMethods.get(JUnit4ReflectionUtil.getClassName(description));
                                if (methods == null) {
                                    return true;
                                }
                                String methodName = JUnit4ReflectionUtil.getMethodName(description);
                                if (methods.contains(methodName)) {
                                    return true;
                                }
                                if (name != null) {
                                    return methodName.endsWith(name) && methods.contains(methodName.substring(0, methodName.length() - name.length()));
                                }
                                final Class testClass = description.getTestClass();
                                if (testClass != null) {
                                    final RunWith classAnnotation = (RunWith) testClass.getAnnotation(RunWith.class);
                                    if (classAnnotation != null && Parameterized.class.isAssignableFrom(classAnnotation.value())) {
                                        final int idx = methodName.indexOf("[");
                                        if (idx > -1) {
                                            return methods.contains(methodName.substring(0, idx));
                                        }
                                    }
                                }
                                return false;
                            }
                            return true;
                        }

                        public String describe() {
                            return "Tests";
                        }
                    });
                } finally {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        } else {
            int index = suiteClassName.indexOf(',');
            if (index != -1) {
                final Class clazz = loadTestClass(suiteClassName.substring(0, index));
                final String methodName = suiteClassName.substring(index + 1);
                final RunWith clazzAnnotation = (RunWith) clazz.getAnnotation(RunWith.class);
                final Description testMethodDescription = Description.createTestDescription(clazz, methodName);
                if (clazzAnnotation == null) {
                    //do not override external runners
                    try {
                        final Method method = clazz.getMethod(methodName, null);
                        if (method != null && notForked && (method.getAnnotation(Ignore.class) != null || clazz.getAnnotation(Ignore.class) != null)) {
                            //override ignored case only
                            final Request classRequest = JUnit45ClassesRequestBuilder.createIgnoreIgnoredClassRequest(clazz, true);
                            final Filter ignoredTestFilter = Filter.matchMethodDescription(testMethodDescription);
                            return classRequest.filterWith(new Filter() {

                                public boolean shouldRun(Description description) {
                                    return ignoredTestFilter.shouldRun(description);
                                }

                                public String describe() {
                                    return "Ignored " + methodName;
                                }
                            });
                        }
                    } catch (Throwable ignored) {
                    //return simple method runner
                    }
                } else {
                    final Request request = getParameterizedRequest(name, methodName, clazz, clazzAnnotation);
                    if (request != null) {
                        return request;
                    }
                }
                try {
                    if (clazz.getMethod("suite", new Class[0]) != null && !methodName.equals("suite")) {
                        return Request.classWithoutSuiteMethod(clazz).filterWith(testMethodDescription);
                    }
                } catch (Throwable e) {
                //ignore
                }
                final Filter methodFilter;
                try {
                    methodFilter = Filter.matchMethodDescription(testMethodDescription);
                } catch (NoSuchMethodError e) {
                    return Request.method(clazz, methodName);
                }
                return Request.aClass(clazz).filterWith(new Filter() {

                    public boolean shouldRun(Description description) {
                        if (description.isTest() && description.getDisplayName().startsWith("warning(junit.framework.TestSuite$")) {
                            return true;
                        }
                        return methodFilter.shouldRun(description);
                    }

                    public String describe() {
                        return methodFilter.describe();
                    }
                });
            } else if (name != null && suiteClassNames.length == 1) {
                final Class clazz = loadTestClass(suiteClassName);
                if (clazz != null) {
                    final RunWith clazzAnnotation = (RunWith) clazz.getAnnotation(RunWith.class);
                    final Request request = getParameterizedRequest(name, null, clazz, clazzAnnotation);
                    if (request != null) {
                        return request;
                    }
                }
            }
            appendTestClass(result, suiteClassName);
        }
    }
    if (result.size() == 1) {
        final Class clazz = (Class) result.get(0);
        try {
            if (clazz.getAnnotation(Ignore.class) != null) {
                //override ignored case only
                return JUnit45ClassesRequestBuilder.createIgnoreIgnoredClassRequest(clazz, false);
            }
        } catch (ClassNotFoundException e) {
        //return simple class runner
        }
        return Request.aClass(clazz);
    }
    return Request.classes(getArrayOfClasses(result));
}
Also used : Ignore(org.junit.Ignore) Description(org.junit.runner.Description) Request(org.junit.runner.Request) IOException(java.io.IOException) Method(java.lang.reflect.Method) RunWith(org.junit.runner.RunWith) Parameterized(org.junit.runners.Parameterized) Filter(org.junit.runner.manipulation.Filter) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 2 with RunWith

use of org.junit.runner.RunWith in project judge by zjnu-acm.

the class MockGenerator method test.

@Test
public void test() throws IOException {
    Gson gson = new Gson();
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
    Map<Class<?>, List<Info>> map = handlerMethods.entrySet().stream().map(entry -> new Info(entry.getValue(), entry.getKey())).collect(Collectors.groupingBy(info -> info.getHandlerMethod().getMethod().getDeclaringClass()));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw, true);
    for (Map.Entry<Class<?>, List<Info>> entry : map.entrySet()) {
        Class<?> key = entry.getKey();
        List<Info> value = entry.getValue();
        if (!accept(key, value)) {
            continue;
        }
        value.sort(Comparator.comparing(info -> info.getHandlerMethod().getMethod(), Comparator.comparing(method -> method.getDeclaringClass().getName().replace(".", "/") + "." + method.getName() + ":" + org.springframework.asm.Type.getMethodDescriptor(method), toMethodComparator(key))));
        TestClass testClass = new TestClass(key, "@AutoConfigureMockMvc", "@RunWith(SpringRunner.class)", "@Slf4j", "@SpringBootTest(classes = " + mainClass.getSimpleName() + ".class)", "@Transactional", "@WebAppConfiguration");
        testClass.addImport(mainClass);
        testClass.addImport(AutoConfigureMockMvc.class);
        testClass.addImport(RunWith.class);
        testClass.addImport(SpringRunner.class);
        testClass.addImport(Slf4j.class);
        testClass.addImport(SpringBootTest.class);
        testClass.addImport(Transactional.class);
        testClass.addImport(WebAppConfiguration.class);
        testClass.addImport(Autowired.class);
        testClass.addField(MockMvc.class, "mvc", "@Autowired");
        for (Info info : value) {
            RequestMappingInfo requestMappingInfo = info.getRequestMappingInfo();
            Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
            String requestMethod = requestMethods.isEmpty() ? "post" : requestMethods.iterator().next().toString().toLowerCase();
            HandlerMethod handlerMethod = info.getHandlerMethod();
            String url = gson.toJson(requestMappingInfo.getPatternsCondition().getPatterns().iterator().next());
            generate(key, requestMappingInfo, handlerMethod, url, testClass, requestMethod);
        }
        testClass.write(out);
        Path to = outputDir.resolve(key.getName().replace(".", "/") + "Test.java");
        Files.createDirectories(to.getParent());
        Files.write(to, sw.toString().replace("\t", "    ").getBytes(StandardCharsets.UTF_8));
        sw.getBuffer().setLength(0);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) ClassPool(org.apache.ibatis.javassist.ClassPool) Spliterators(java.util.Spliterators) Autowired(org.springframework.beans.factory.annotation.Autowired) HandlerMethod(org.springframework.web.method.HandlerMethod) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Gson(com.google.gson.Gson) Locale(java.util.Locale) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) SpringRunner(org.springframework.test.context.junit4.SpringRunner) Method(java.lang.reflect.Method) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) WebAppConfiguration(org.springframework.test.context.web.WebAppConfiguration) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) MediaType(org.springframework.http.MediaType) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Modifier(java.lang.reflect.Modifier) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) Spliterator(java.util.Spliterator) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) MockMvc(org.springframework.test.web.servlet.MockMvc) RequestBody(org.springframework.web.bind.annotation.RequestBody) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) HttpServletRequest(javax.servlet.http.HttpServletRequest) Parameter(java.lang.reflect.Parameter) MvcResult(org.springframework.test.web.servlet.MvcResult) StreamSupport(java.util.stream.StreamSupport) Application(cn.edu.zjnu.acm.judge.Application) Files(java.nio.file.Files) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) CtMethod(org.apache.ibatis.javassist.CtMethod) Consumer(java.util.function.Consumer) AutoConfigureMockMvc(org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc) Paths(java.nio.file.Paths) ReflectionUtils(org.springframework.util.ReflectionUtils) MultipartFile(org.springframework.web.multipart.MultipartFile) Comparator(java.util.Comparator) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) Transactional(org.springframework.transaction.annotation.Transactional) Path(java.nio.file.Path) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Gson(com.google.gson.Gson) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) HandlerMethod(org.springframework.web.method.HandlerMethod) StringWriter(java.io.StringWriter) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) PrintWriter(java.io.PrintWriter) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 3 with RunWith

use of org.junit.runner.RunWith in project buck by facebook.

the class JUnitRunner method mightBeATestClass.

/**
   * Guessing whether or not a class is a test class is an imperfect
   * art form.
   */
private boolean mightBeATestClass(Class<?> klass) {
    if (klass.getAnnotation(RunWith.class) != null) {
        // If the class is explicitly marked with @RunWith, it's a test class.
        return true;
    }
    // Since no RunWith annotation, using standard runner, which requires
    // test classes to be non-abstract/non-interface
    int klassModifiers = klass.getModifiers();
    if (Modifier.isInterface(klassModifiers) || Modifier.isAbstract(klassModifiers)) {
        return false;
    }
    // Since no RunWith annotation, using standard runner, which requires
    // test classes to have exactly one public constructor (that has no args).
    // Classes may have (non-public) constructors (with or without args).
    boolean foundPublicNoArgConstructor = false;
    for (Constructor<?> c : klass.getConstructors()) {
        if (Modifier.isPublic(c.getModifiers())) {
            if (c.getParameterCount() != 0) {
                return false;
            }
            foundPublicNoArgConstructor = true;
        }
    }
    if (!foundPublicNoArgConstructor) {
        return false;
    }
    // If the class has a JUnit4 @Test-annotated method, it's a test class.
    boolean hasAtLeastOneTest = false;
    for (Method m : klass.getMethods()) {
        if (Modifier.isPublic(m.getModifiers()) && m.getParameters().length == 0 && m.getAnnotation(Test.class) != null) {
            hasAtLeastOneTest = true;
            break;
        }
    }
    return hasAtLeastOneTest;
}
Also used : Method(java.lang.reflect.Method) RunWith(org.junit.runner.RunWith)

Example 4 with RunWith

use of org.junit.runner.RunWith in project j2objc by google.

the class JUnitTestRunner method isJUnit4TestClass.

/**
   * @return true if {@param cls} is {@link JUnit4} annotated.
   */
protected boolean isJUnit4TestClass(Class<?> cls) {
    // Need to find test classes, otherwise crashes with b/11790448.
    if (!cls.getName().endsWith("Test")) {
        return false;
    }
    // Check the annotations.
    Annotation annotation = cls.getAnnotation(RunWith.class);
    if (annotation != null) {
        RunWith runWith = (RunWith) annotation;
        Object value = runWith.value();
        if (value.equals(JUnit4.class) || value.equals(Suite.class)) {
            return true;
        }
    }
    return false;
}
Also used : Suite(org.junit.runners.Suite) RunWith(org.junit.runner.RunWith) Annotation(java.lang.annotation.Annotation) JUnit4(org.junit.runners.JUnit4)

Example 5 with RunWith

use of org.junit.runner.RunWith in project kanonizo by kanonizo.

the class JUnit4TestRunner method getRequest.

private Request getRequest(TestCase tc) {
    Class<?> testClass = tc.getTestClass();
    Method testMethod = tc.getMethod();
    try {
        final RunWith runWith = testClass.getAnnotation(RunWith.class);
        if (runWith != null) {
            final Class<? extends Runner> runnerClass = runWith.value();
            if (runnerClass.isAssignableFrom(Parameterized.class)) {
                try {
                    if (tc instanceof ParameterisedTestCase) {
                        ParameterisedTestCase ptc = (ParameterisedTestCase) tc;
                        Class.forName(// ignore IgnoreIgnored for junit4.4 and <
                        "org.junit.runners.BlockJUnit4ClassRunner");
                        return Request.runner(new ParameterizedMethodRunner(testClass, testMethod.getName(), ptc.getParameters()));
                    }
                } catch (Throwable thrown) {
                    logger.error(thrown);
                }
            }
        } else {
            if (testMethod != null && testMethod.getAnnotation(Ignore.class) != null) {
                // override ignored case only
                final Request classRequest = new ClassRequest(testClass) {

                    public Runner getRunner() {
                        try {
                            return new IgnoreIgnoredTestJUnit4ClassRunner(testClass);
                        } catch (Exception ignored) {
                        }
                        return super.getRunner();
                    }
                };
                return classRequest.filterWith(Description.createTestDescription(testClass, testMethod.getName()));
            }
        }
    } catch (Exception ignored) {
        logger.error(ignored);
    }
    return Request.method(testClass, testMethod.getName());
}
Also used : ParameterisedTestCase(org.kanonizo.framework.objects.ParameterisedTestCase) Request(org.junit.runner.Request) ClassRequest(org.junit.internal.requests.ClassRequest) Method(java.lang.reflect.Method) FrameworkMethod(org.junit.runners.model.FrameworkMethod) RunWith(org.junit.runner.RunWith) ClassRequest(org.junit.internal.requests.ClassRequest) AssumptionViolatedException(org.junit.AssumptionViolatedException)

Aggregations

RunWith (org.junit.runner.RunWith)12 Method (java.lang.reflect.Method)5 List (java.util.List)3 JUnit4 (org.junit.runners.JUnit4)3 IOException (java.io.IOException)2 Annotation (java.lang.annotation.Annotation)2 Modifier (java.lang.reflect.Modifier)2 Arrays (java.util.Arrays)2 Set (java.util.Set)2 Suite (org.junit.runners.Suite)2 Application (cn.edu.zjnu.acm.judge.Application)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Objects (com.google.common.base.Objects)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Truth.assertThat (com.google.common.truth.Truth.assertThat)1 Gson (com.google.gson.Gson)1 PsiUtils (com.google.idea.blaze.base.lang.buildfile.psi.util.PsiUtils)1 WorkspacePath (com.google.idea.blaze.base.model.primitives.WorkspacePath)1 BlazeRunConfigurationProducerTestCase (com.google.idea.blaze.base.run.producer.BlazeRunConfigurationProducerTestCase)1 Info (com.intellij.execution.lineMarker.RunLineMarkerContributor.Info)1