JAX-RS not responding at all (404) - eclipse

I'm using Eclipse 2020-03, Gradle and Tomcat. all I did follows.
Installing gradle through eclipse marketplace.
making gradle project.
adding those on build.gradle dependencies
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:28.2-jre'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.27'
compile group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.27'
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.4.0-b180830.0359'
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.27'
}
adding "rest" package on src/main/java
adding ApplicationConfig.java and RestApiService.java on rest package.
ApplicationConfig.java
package rest;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/api")
public class ApplicationConfig extends Application {
#Override
public Map<String, Object> getProperties(){
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("jersey.config.server.provider.packages", "A_UnivG.rest");
return properties;
}
}
RestApiService.java
package rest;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import Data.*;
#Path("/Data")
public class RestApiService {
Logger logger = Logger.getLogger("RestApiService");
IntegrationDAO dao = new IntegrationDAO();
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String getHello() {return "Hello";}
}
and when I try to request http://localhost:portnumber/A_UnivG/api/Data/hello it spits out only 404 error.
cannot figure out why.
My project works with plain jsp files. I have a JSP page which uses DAO Read but it works just fine. well, that shouldn't be a problem I just tried hello world and it doesn't work at all.

Related

Junit class failing after ACS Commons version upgrade to 5.3.4

I upgraded ACS Commons version from 5.0.6 to 5.3.4 in my project and now can see most of the test classes failing with below error
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [io.wcm.testing.mock.aem.junit5.AemContext arg0] in method [void com.test.test.core.filters.LoggingFilterTest.doFilter(io.wcm.testing.mock.aem.junit5.AemContext) throws java.io.IOException,javax.servlet.ServletException]: Could not create io.wcm.testing.mock.aem.junit5.ResourceResolverMockAemContext instance.
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:232)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:176)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:137)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:118)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
a
Caused by: org.reflections.ReflectionsException: Scanner TypeAnnotationsScanner was not configured
at org.reflections.Store.get(Store.java:39)
at org.reflections.Store.get(Store.java:61)
at org.reflections.Store.get(Store.java:46)
Please find below my test class. I am using JUnit version as below
<dependency>
<groupId>io.wcm</groupId>
<artifactId>io.wcm.testing.aem-mock.junit5</artifactId>
<version>4.0.4</version>
<scope>test</scope>
</dependency>
Attaching the class below:
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.LoggingEvent;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
#ExtendWith(AemContextExtension.class)
class LoggingFilterTest {
private LoggingFilter fixture = new LoggingFilter();
private TestLogger logger = TestLoggerFactory.getTestLogger(fixture.getClass());
#BeforeEach
void setup() {
TestLoggerFactory.clear();
}
#Test
void doFilter(AemContext context) throws IOException, ServletException {
MockSlingHttpServletRequest request = context.request();
MockSlingHttpServletResponse response = context.response();
MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo();
requestPathInfo.setResourcePath("/content/test");
requestPathInfo.setSelectorString("selectors");
fixture.init(mock(FilterConfig.class));
fixture.doFilter(request, response, mock(FilterChain.class));
fixture.destroy();
List<LoggingEvent> events = logger.getLoggingEvents();
assertEquals(0, events.size());
}
}
Does anyone know why it is failing with the ACS Commons version change?
This is like breaking lot many junit test classes

Getting error while connecting to jpa using micronaut-data-hibernate-jpa library

I want to use JPA for micronaut. For that I am using io.micronaut.data:micronaut-data-hibernate-jpa:1.0.0.M1 library. Whenever I run my application and hit the endpoint to get the data, I get the following error:
{
message: "Internal Server Error: No backing RepositoryOperations configured for repository. Check your configuration and try again"
}
I tried looking up for errors but I couldn't find one. Attaching my files here. Please help.
build.gradle
plugins {
id "net.ltgt.apt-eclipse" version "0.21"
id "com.github.johnrengelman.shadow" version "5.0.0"
id "application"
}
version "0.1"
group "micronaut.test"
repositories {
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
configurations {
// for dependencies that are needed for development only
developmentOnly
}
dependencies {
annotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
annotationProcessor "io.micronaut:micronaut-inject-java"
annotationProcessor "io.micronaut:micronaut-validation"
annotationProcessor "org.projectlombok:lombok:1.16.20"
annotationProcessor 'io.micronaut.data:micronaut-data-processor:1.0.0.M1'
implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
compile 'io.micronaut.data:micronaut-data-hibernate-jpa:1.0.0.M1'
implementation "io.micronaut:micronaut-inject"
implementation "io.micronaut:micronaut-validation"
implementation "io.micronaut:micronaut-runtime"
implementation "io.micronaut:micronaut-http-server-netty"
implementation "io.micronaut:micronaut-http-client"
implementation 'nl.topicus:spanner-jdbc:1.1.5'
runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
testAnnotationProcessor platform("io.micronaut:micronaut-bom:$micronautVersion")
testAnnotationProcessor "io.micronaut:micronaut-inject-java"
testImplementation "org.junit.jupiter:junit-jupiter-api"
testCompile "org.junit.jupiter:junit-jupiter-engine:5.1.0"
testImplementation "io.micronaut.test:micronaut-test-junit5"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine"
}
test.classpath += configurations.developmentOnly
mainClassName = "micronaut.test.Application"
// use JUnit 5 platform
test {
useJUnitPlatform()
}
tasks.withType(JavaCompile){
options.encoding = "UTF-8"
options.compilerArgs.add('-parameters')
}
shadowJar {
mergeServiceFiles()
}
run.classpath += configurations.developmentOnly
run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
Repository:
package micronaut.test.repo;
import io.micronaut.data.annotation.Repository;
import io.micronaut.data.repository.CrudRepository;
import micronaut.test.entity.Partner;
#Repository
public interface PartnerRepository extends CrudRepository<Partner,Integer> {
}
Service:
package micronaut.test.service;
import micronaut.test.entity.Partner;
import micronaut.test.repo.PartnerRepository;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
#Singleton
public class SpannerService {
private PartnerRepository partnerRepository;
#Inject
public SpannerService(PartnerRepository partnerRepository) {
this.partnerRepository = partnerRepository;
}
public List<Partner> getPartners() {
return (List<Partner>) partnerRepository.findAll();
}
}
Controller:
package micronaut.test.controller;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import micronaut.test.entity.Partner;
import micronaut.test.service.SpannerService;
import javax.inject.Inject;
import java.util.List;
#Controller("/micronaut")
public class MainController {
private SpannerService spannerService;
#Inject
public MainController(SpannerService spannerService) {
this.spannerService = spannerService;
}
#Get("/data")
#Produces(MediaType.APPLICATION_JSON)
public List<Partner> getPartners() {
return spannerService.getPartners();
}
}
stacktrace:
io.micronaut.context.exceptions.ConfigurationException: No backing RepositoryOperations configured for repository. Check your configuration and try again
at io.micronaut.data.intercept.DataIntroductionAdvice.findInterceptor(DataIntroductionAdvice.java:108)
at io.micronaut.data.intercept.DataIntroductionAdvice.intercept(DataIntroductionAdvice.java:76)
at io.micronaut.aop.MethodInterceptor.intercept(MethodInterceptor.java:40)
at io.micronaut.aop.chain.InterceptorChain.proceed(InterceptorChain.java:150)
at micronaut.test.repo.PartnerRepository$Intercepted.findAll(Unknown Source)
at micronaut.test.service.SpannerService.getPartners(SpannerService.java:22)
at micronaut.test.controller.MainController.getPartners(MainController.java:32)
at micronaut.test.controller.$MainControllerDefinition$$exec2.invokeInternal(Unknown Source)
at io.micronaut.context.AbstractExecutableMethod.invoke(AbstractExecutableMethod.java:144)
at io.micronaut.context.DefaultBeanContext$BeanExecutionHandle.invoke(DefaultBeanContext.java:2792)
at io.micronaut.web.router.AbstractRouteMatch.execute(AbstractRouteMatch.java:235)
at io.micronaut.web.router.RouteMatch.execute(RouteMatch.java:122)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$buildResultEmitter$19(RoutingInBoundHandler.java:1408)
at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:71)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableMap.subscribeActual(FlowableMap.java:37)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14868)
at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:52)
at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:68)
at io.reactivex.Flowable.subscribe(Flowable.java:14918)
at io.reactivex.Flowable.subscribe(Flowable.java:14865)
at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [io.micronaut.data.operations.RepositoryOperations] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:1903)
at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:582)
at io.micronaut.data.intercept.DataIntroductionAdvice.findInterceptor(DataIntroductionAdvice.java:105)
... 43 common frames omitted
Micronaut currently supports only Tomcat JDBC, Apache DBCP2 and Hikari data sources providers out of the box (see https://micronaut-projects.github.io/micronaut-sql/latest/guide/#jdbc).
You can add this line into your build.gradle which adds Tomcat JDBC Data Source provider implementation into your project:
runtime "io.micronaut.configuration:micronaut-jdbc-tomcat"
Or you can choose another implementations like Apache DBCP2:
runtime "io.micronaut.configuration:micronaut-jdbc-dbcp"
Or Hikari:
runtime "io.micronaut.configuration:micronaut-jdbc-hikari"
For nl.topicus:spanner-jdbc data source provider you have to implement your own DatasourceFactory and DatasourceConfiguration for Micronaut because there is no one yet.
You can inspire your self in io.micronaut.configuration:micronaut-jdbc-tomcat. Sources are here: https://github.com/micronaut-projects/micronaut-sql/tree/master/jdbc-tomcat/src/main/java/io/micronaut/configuration/jdbc/tomcat
For example DatasourceFactory can then look like this:
#Factory
public class DatasourceFactory implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(DatasourceFactory.class);
private List<nl.topicus.jdbc.CloudSpannerDataSource> dataSources = new ArrayList<>(2);
private final DataSourceResolver dataSourceResolver;
/**
* Default constructor.
* #param dataSourceResolver The data source resolver
*/
public DatasourceFactory(#Nullable DataSourceResolver dataSourceResolver) {
this.dataSourceResolver = dataSourceResolver == null ? DataSourceResolver.DEFAULT : dataSourceResolver;
}
/**
* #param datasourceConfiguration A {#link DatasourceConfiguration}
* #return An Apache Tomcat {#link DataSource}
*/
#Context
#EachBean(DatasourceConfiguration.class)
public DataSource dataSource(DatasourceConfiguration datasourceConfiguration) {
nl.topicus.jdbc.CloudSpannerDataSource ds = new nl.topicus.jdbc.CloudSpannerDataSource();
ds.setJdbcUrl(datasourceConfiguration.getJdbcUrl());
...
dataSources.add(ds);
return ds;
}
#Override
#PreDestroy
public void close() {
for (nl.topicus.jdbc.CloudSpannerDataSource dataSource : dataSources) {
try {
dataSource.close();
} catch (Exception e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Error closing data source [" + dataSource + "]: " + e.getMessage(), e);
}
}
}
}
}
Anyway you can still use Google Cloud Spanner DB with Data Source providers like Hikari and Apache DBCP2. For example:
runtime 'nl.topicus:spanner-jdbc:1.1.5'
runtime "io.micronaut.configuration:micronaut-jdbc-hikari"
The first line adds JDBC driver and the second line adds Data Source provider which will use the spanner-jdbc JDBC driver.
It is known that the Google Cloud Spanner uses another dialect than other databases for Hibernate ORM. I think that this dialect is pretty new. Take a look over this repository 1. Maybe it will be useful for you, not necessary for solving your current issue, but giving you some other perspective.

Jersey 1.9 webapp on Tomcat 8 (Eclipse) upgrade to 1.19.1 cause 404 error

if I change the jersey version to a higher one than 1.9 then a 404 error returns when I try to run the servlet.
Here are some details of my setting:
- Tomcat 8
- Eclipse Luna
- Maven for integrating the lib
I guess there are maybe changes in the syntax of the RestFul service provide since 1.9, but I'm not sure. So here is the servlet code:
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/helloWorldREST")
public class HelloWorldREST {
#GET
#Path("/{parameter}")
public Response responseMsg( #PathParam("parameter") String parameter,
#DefaultValue("Nothing to say") #QueryParam("value") String value) {
String output = "Hello from: " + parameter + " : " + value;
return Response.status(200).entity(output).build();
}
}

POST Request not working with CORS (Java EE7, Glassfish 4.1, JAX-RS 2.0)

I used NetBeans IDE 8.0.1 "RESTful Web Services from database" wizard to map my table objects with JPA and JAX-RS 2.0.
After the classes were created, with the project options "Test RESTful Web Services", NetBeans itself creates an interface (HTML, css).
This works fine in my localhost. I can connect to my database from the Web Services created, sending GET and POST (JSON) Requests.
Now, I need to access from another domain different from my localhost, so I tried with CORS.
Searching diferent post I used this code:
package CORS;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;
#Provider
#PreMatching
public class CORSResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
And with this ApplicationConfig class created, the resource (CORSRequestFilter) was added:
package entities.service;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(CORS.CORSResponseFilter.class);
resources.add(entities.service.AppSettingsFacadeREST.class);
resources.add(entities.service.CategoryFacadeREST.class);
resources.add(entities.service.CityFacadeREST.class);
resources.add(entities.service.EmailInitialSubscriptionFacadeREST.class);
resources.add(entities.service.IdentityProviderFacadeREST.class);
resources.add(entities.service.ItemFacadeREST.class);
resources.add(entities.service.ItemHistoryFacadeREST.class);
resources.add(entities.service.ItemStatusFacadeREST.class);
resources.add(entities.service.PhotoFacadeREST.class);
resources.add(entities.service.UserFacadeREST.class);
resources.add(entities.service.WantedItemsFacadeREST.class);
}
}
And it works perfectly for a while!
I was able to connect to my database to my Glassfish server from another domain using the RESTful web services just fine. I even develop an AngularJS app and could use the RSWebServices too.
Then I started to receive this error:
XMLHttpRequest cannot load http://xx.x.xxx.xx:8080/freeproject/webresources/entities.emailinitialsubscription. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxxxxxx.com' is therefore not allowed access. The response had HTTP status code 400.
The preflight request is returned with a status 200 OK. But the POST request is failed.
Searching on internet I found that Oracle itself https://blogs.oracle.com/theaquarium/entry/supporting_cors_in_jax_rs tells me to follow this post:
http://www.developerscrappad.com/1781/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-cors-on-rest-how-to-make-rest-apis-accessible-from-a-different-domain/
So, I tried that and I added a new class: resources.add(CORS.CORSRequestFilter.class):
package CORS;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
#Provider
#PreMatching
public class CORSRequestFilter implements ContainerRequestFilter {
#Override
public void filter( ContainerRequestContext requestCtx ) throws IOException {
String path = requestCtx.getUriInfo().getPath();
// IMPORTANT!!! First, Acknowledge any pre-flight test from browsers for this case before validating the headers (CORS stuff)
if ( requestCtx.getRequest().getMethod().equals( "OPTIONS" ) ) {
requestCtx.abortWith( Response.status( Response.Status.OK ).build() );
}
}
}
But it doesn't work. The abortWith function stop the chain of requests and the POST request is never sent.
What can I do here? Any help will be highly appreciated.

Can't run Scalatest with Gradle

task scalaTest(dependsOn: testClasses) << {
description = 'Runs Scalatest suite'
ant.taskdef(name: 'scalatest',
classname: 'org.scalatest.tools.ScalaTestAntTask',
classpath: sourceSets.test.runtimeClasspath.asPath
)
ant.scalatest(runpath: sourceSets.test.output.classesDir,
haltonfailure: 'true', fork: 'false') {
reporter(type: 'stdout')
}
}
I run gradle scalaTest and I get:
* What went wrong:
Execution failed for task ':scalaTest'.
> java.lang.NoClassDefFoundError: scala/reflect/ClassManifest$
I am using Scala 2.10.2 and Gradle 1.7
dependencies {
compile 'org.scala-lang:scala-library:2.10.2'
testCompile 'org.scalatest:scalatest:1.3'
testCompile 'org.scalamock:scalamock_2.10:3.0.1'
}
What's wrong??
I do not know how to solve this one, but I can offer you a workaround. Annotate your test classes with #RunWith(classOf[JUnitRunner]), like this:
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
#RunWith(classOf[JUnitRunner])
class MyTest extends FunSpec{
}
and then, gradle test should work.
Edit:
My dependencies:
compile "org.scala-lang:scala-library:2.10.1"
testCompile "org.scalatest:scalatest_2.10:1.9.1"
You can put the following in your build.gradle:
task spec(dependsOn: ['testClasses'], type: JavaExec) {
main = 'org.scalatest.tools.Runner'
args = ['-R', 'build/classes/scala/test', '-o']
classpath = sourceSets.test.runtimeClasspath
}
Note: The path my be different depending on the gradle version as pointed out in the comments by #MikeRylander. Before gradle 4 it used to be 'build/classes/test'.
Then just run gradle spec to execute your tests.
I named the task spec because there already is a test task. I don't know if you can override the default test task.
You can look up the available options here.
This response may be a bit late. But for one using scala with gradle (5.x), the following works.
Add the following plugin to gradle.
plugins {
id "com.github.maiflai.scalatest" version "0.25"
}
To run the code
> gradle test
As a bonus the test results from the above plugin would also be reported better than the default report.
rarry is correct. And even better, you can annotate a base test class with #RunWith(classOf[JUnitRunner]) once to cause all of your ScalaTest tests to run with the JUnit runner (assuming they extend the base class), e.g.:
import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner
#RunWith(classOf[JUnitRunner])
abstract class UnitSpec extends FlatSpec with Matchers
As of Gradle 3.2.1, following root build.gradle runs both JUnit and ScalaTest code. This code is for multi-project build, enabled via settings.gradle, that's why subprojects used.
Plus, it's on purpose uses explicit Gradle API, to minimize Gradle DSL magic.
description = 'root project'
def enableScalaTest(Project project) {
Task scalaTest = project.task(
[
'dependsOn': 'testClasses',
'description': 'Runs ScalaTest tests in the project'
],
'scalaTest',
{
ext.inputDir = project.tasks.getByName('compileTestScala').destinationDir
inputs.dir(ext.inputDir)
}
)
scalaTest.doLast({
ant.taskdef(name: 'scalatest',
classname: 'org.scalatest.tools.ScalaTestAntTask',
classpath: project.sourceSets.test.runtimeClasspath.asPath)
ant.scalatest(runpath: ext.inputDir,
fork: 'false',
haltonfailure: 'true')
{ reporter(type: 'stdout') }
})
project.getTasks().getByName('build').dependsOn(scalaTest)
}
subprojects {
apply plugin: 'scala'
repositories {
mavenCentral()
}
dependencies {
compile 'org.scala-lang:scala-library:2.12.1'
testCompile 'junit:junit:4.12'
testCompile 'org.scalatest:scalatest_2.12:3.0.1'
}
enableScalaTest(delegate)
}