It's impossible to unit-test a Spring Data JPA #Query, really? - unit-testing

First of all, the goal. What is unit test? Unit test is a test that tests the smallest piece of functionality, opposite to integration tests that test much more e.g.:
test that spawns production ApplicationContext in any means or any form is NOT a unit test;
test that touches or even aware of the Application (marked with #SpringBootApplication) class is NOT a unit test;
test that loads something from src/main/resources is NOT a unit test
test that loads external configuration from Spring Cloud Config server is definatelly not a unit test;
unit test of a repository must not start (or even know about) web, mvc or security concerns.
So, how to write a unit test for a Spring Data JPA repository? (or so popular and loved framework doesn't support pure unit test for such a thing?)
My project: Spring Cloud (Cloud Counfig service, Security OAuth2 service, eureka, zuul, authentication, authorization etc.)
Let's try to test the simplest repository:
public interface StudentRepository extends CrudRepository<Student, Integer> {
Optional<Student> findByStudentCode(Integer studentCode);
Optional<Student> findTopByOrderByStudentCodeDesc();
#Query(value = "SELECT COUNT(*) = 0 FROM t_student WHERE regexp_replace(LOWER(student_name), '\\s', '', 'g') = regexp_replace(LOWER(:suspect), '\\s', '', 'g')", nativeQuery = true)
boolean isStudentNameSpeciallyUnique(#Param("suspect") String studentName);
}
The student entity will have: id, code (natural ID), name, age. Nothing special.
And here is the test. We need a SUT (our repository) and entity manager to prepopulate the SUT. So:
#RunWith(SpringRunner.class)
#DataJpaTest // <-- loads full-blown production app context and fails!
public class StudentRepositoryTest {
#Autowired
TestEntityManager manager;
#Autowired
StudentRepository repository;
#Test
public void findByStudentCode_whenNoSuch_shouldReturnEmptyOptional() {
final int invalidStudentCode = 321;
Optional<Student> student = repository.findByStudentCode(invalidStudentCode);
assertFalse(student.isPresent());
}
}
Attemp to run it produces this:
...
2019-01-01 18:32:10.750 INFO 15868 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#2d72f75e: startup date [Tue Jan 01 18:32:10 EET 2019]; root of context hierarchy
2019-01-01 18:32:11.294 INFO 15868 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2019-01-01 18:32:11.421 INFO 15868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$9ed1a748] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.6.RELEASE)
2019-01-01 18:32:30.694 INFO 15868 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888\
...
The #DataJpaTest searches upwards the package hierrarchy and loads the production application:
package org.givespring.atry.university.studentservice;
#EnableResourceServer
#EnableJpaAuditing
#SpringBootApplication(scanBasePackages = "org.givespring.atry.university") // to discover MicroserviceProperties and custom usercontext stuff
public class StudentServiceApp {
public static void main(String[] args) {
SpringApplication.run(StudentServiceApp.class, args);
}
}
As a result, the error:
2019-01-01 18:32:32.789 ERROR 15868 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Unable to retrieve #EnableAutoConfiguration base packages
at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:76) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:79) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$1.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:73) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.lambda$getCandidates$2(RepositoryConfigurationSourceSupport.java:77) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
at org.springframework.data.util.LazyStreamable.stream(LazyStreamable.java:50) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
at org.springframework.data.util.LazyStreamable.iterator(LazyStreamable.java:41) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
at org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:87) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:126) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions(AbstractRepositoryConfigurationSourceSupport.java:60) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:358) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_121]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:357) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:146) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:118) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:271) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:91) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:692) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:530) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) [spring-boot-test-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) [spring-boot-test-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
2019-01-01 18:32:32.792 INFO 15868 --- [ main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#6a2eea2a: startup date [Tue Jan 01 18:32:32 EET 2019]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#2d72f75e

In shortcut unit test is a fast test of a small unit. What is a unit depends on the developer or architecture guidelines. It can be any small, testable piece of code, such as a method or a class.
Also, If you think about it, there's no code you write for your repositories. You depend of Spring Platform. If you find some bug, feel free to raise a ticket
So there's no need to write any unit tests for Spring Data JPA repository methods.
If you need to write a unit test for a Spring Data JPA repository, I suppose your concern is related to methods: save, delete, findOne, findAll, etc. In this case, as you can see, this is not small, so an integration test is required.
This repository contains an example of integration test with spring jpa repository methods:
https://github.com/jrichardsz/spring-boot-templates/blob/master/003-hql-database-with-integration-test/src/test/java/test/CustomerRepositoryIntegrationTest.java
References:
https://stackoverflow.com/a/23442457/3957754
https://www.quora.com/What-is-the-real-efficiency-of-unit-testing

Related

[Amazon](500150) SocketTimeoutException. Works locally but not on Lambda [Redshift, Spring Data JDBC, Spring Boot]

I am working on a simple API to query Redshift and I am encountering nothing but problems. The current one is that I am getting a SocketTimeoutException when I deploy it to Lambda. Googling this exception has tons of recommendations to add "client CIDR/IP address to the VPC security group". However, my credentials (and IP) work fine for me to access the Redshift DB from my DB Client (DBeaver), and when I run my Spring Boot application locally and call it from Postman. But once it is on Lambda I get the SocketTimeoutException.
I am reaching out to the team to check if I do need to whitelist an IP, but the headache I was having before this was about Spring Boot taking too long to build causing other types of time outs and I have a feeling that this issue has more to do with Spring Boot than it does with my Redshift connection.
Reasons I suspect this:
1. as I mentioned, I have had timeout issues for days but it only switched to the socket timeout when I went from variations of the suggested:
public StreamLambdaHandler() throws ContainerInitializationException {
long startTime = Instant.now().toEpochMilli();
handler = new SpringBootProxyHandlerBuilder()
.defaultProxy()
.asyncInit(startTime)
.springBootApplication(Application.class)
.buildAndInitialize();
}
to what a different API my company is using has:
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
static {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
} catch (ContainerInitializationException e) {
e.printStackTrace();
throw new RuntimeException("Could not initialize Spring Boot application", e);
}
}
2 My company deploys a much heavier api (with many endpoints, service classes, etc) that is only 60kb whereas my single endpoint api I am packaging as shaded with all the dependencies which put it at a whopping 19.6MB! I am guessing this might be affecting the load time?
3 it takes 4.227 seconds to load locally.
Full Stack Trace is really really long, but here is the bit I think is most relevant:
2023-02-06T07:13:30.139-06:00 INIT_START Runtime Version: java:11.v15 Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:blahhalb
2023-02-06T07:13:30.715-06:00 13:13:30.711 [main] INFO com.amazonaws.serverless.proxy.internal.LambdaContainerHandler - Starting Lambda Container Handler
*****Starts app at 7:13:31*****
2023-02-06T07:13:31.634-06:00 . ____ _ __ _ _
2023-02-06T07:13:31.634-06:00 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
2023-02-06T07:13:31.634-06:00 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2023-02-06T07:13:31.634-06:00 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
2023-02-06T07:13:31.634-06:00 ' |____| .__|_| |_|_| |_\__, | / / / /
2023-02-06T07:13:31.634-06:00 =========|_|==============|___/=/_/_/_/
2023-02-06T07:13:31.638-06:00 :: Spring Boot ::
2023-02-06T07:13:31.834-06:00 2023-02-06 13:13:31.833 INFO 9 --- [ main] lambdainternal.AWSLambda : Starting AWSLambda using Java 11.0.14.1 on 169.254.10.245 with PID 9 (/var/runtime/lib/aws-lambda-java-runtime-0.2.0.jar started by sbx_user1051 in /var/task)
2023-02-06T07:13:31.835-06:00 2023-02-06 13:13:31.835 INFO 9 --- [ main] lambdainternal.AWSLambda : No active profile set, falling back to default profiles: default
2023-02-06T07:13:32.722-06:00 2023-02-06 13:13:32.722 INFO 9 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2023-02-06T07:13:32.787-06:00 2023-02-06 13:13:32.787 INFO 9 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 58 ms. Found 1 JDBC repository interfaces.
2023-02-06T07:13:33.194-06:00 2023-02-06 13:13:33.194 INFO 9 --- [ main] c.a.s.p.i.servlet.AwsServletContext : Initializing Spring embedded WebApplicationContext
2023-02-06T07:13:33.194-06:00 2023-02-06 13:13:33.194 INFO 9 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1281 ms
2023-02-06T07:13:33.587-06:00 2023-02-06 13:13:33.585 INFO 9 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-02-06T07:13:40.762-06:00 13:13:40.758 [main] INFO
***** After failing to make connection after 7 seconds, restarts app*****
com.amazonaws.serverless.proxy.internal.LambdaContainerHandler - Starting Lambda Container Handler
2023-02-06T07:13:41.613-06:00 . ____ _ __ _ _
2023-02-06T07:13:41.613-06:00 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
2023-02-06T07:13:41.613-06:00 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
2023-02-06T07:13:41.613-06:00 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
2023-02-06T07:13:41.613-06:00 ' |____| .__|_| |_|_| |_\__, | / / / /
2023-02-06T07:13:41.613-06:00 =========|_|==============|___/=/_/_/_/
2023-02-06T07:13:41.616-06:00 :: Spring Boot ::
2023-02-06T07:13:41.807-06:00 2023-02-06 13:13:41.805 INFO 12 --- [ main] lambdainternal.AWSLambda : Starting AWSLambda using Java 11.0.14.1 on 169.254.10.245 with PID 12 (/var/runtime/lib/aws-lambda-java-runtime-0.2.0.jar started by sbx_user1051 in /var/task)
2023-02-06T07:13:41.807-06:00 2023-02-06 13:13:41.807 INFO 12 --- [ main] lambdainternal.AWSLambda : No active profile set, falling back to default profiles: default
2023-02-06T07:13:42.699-06:00 2023-02-06 13:13:42.699 INFO 12 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2023-02-06T07:13:42.762-06:00 2023-02-06 13:13:42.761 INFO 12 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 56 ms. Found 1 JDBC repository interfaces.
2023-02-06T07:13:43.160-06:00 2023-02-06 13:13:43.160 INFO 12 --- [ main] c.a.s.p.i.servlet.AwsServletContext : Initializing Spring embedded WebApplicationContext
2023-02-06T07:13:43.160-06:00 2023-02-06 13:13:43.160 INFO 12 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1277 ms
2023-02-06T07:13:43.549-06:00 2023-02-06 13:13:43.548 INFO 12 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-02-06T07:14:14.685-06:00 2023-02-06 13:14:14.684 ERROR 12 --- [ main]
*****Tries to make a connection for 31 seconds before giving me the SocketTimeoutException*****
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
2023-02-06T07:14:14.685-06:00 java.sql.SQLException: [Amazon](500150) Error setting/closing connection: SocketTimeoutException.
2023-02-06T07:14:14.685-06:00 at com.amazon.redshift.client.PGClient.connect(Unknown Source) ~[task/:na]
2023-02-06T07:14:14.685-06:00 at com.amazon.redshift.client.PGClient.<init>(Unknown Source) ~[task/:na]
2023-02-06T07:14:14.685-06:00 at com.amazon.redshift.core.PGJDBCConnection.connect(Unknown Source) ~[task/:na]
2023-02-06T07:14:14.685-06:00 at com.amazon.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source) ~[task/:na]
2023-02-06T07:14:14.685-06:00 at com.amazon.jdbc.common.AbstractDriver.connect(Unknown Source) ~[task/:na]
2023-02-06T07:14:14.685-06:00 at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[task/:na]
Is it possible that this is a Spring Boot build timeout exception? or is it much more likely that it is in fact a Redshift connection issue?
SO your use case is to write an AWS Lambda function that can perform CRUD operations on a Redshift cluster? If so, you can implement this use case by using the Java Lambda run-time API.
com.amazonaws.services.lambda.runtime.RequestHandler
To perform Redshift data CRUD operations from Lambda, you can use software.amazon.awssdk.services.redshiftdata.RedshiftDataClient.
Once you setup your Lambda function correctly, you can use the Redshift data client to modify the data. For example:
private RedshiftDataClient getClient() {
Region region = Region.US_WEST_2;
RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder()
.region(region)
.build();
return redshiftDataClient;
}
public void delPost(String id) {
try {
RedshiftDataClient redshiftDataClient = getClient();
String sqlStatement = "DELETE FROM blog WHERE idblog = '" + id + "'";
ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder()
.clusterIdentifier(clusterId)
.database(database)
.dbUser(dbUser)
.sql(sqlStatement)
.build();
redshiftDataClient.executeStatement(statementRequest);
} catch (RedshiftDataException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
ALso - as your Lambda function invokes Amazon Redshift, the IAM role that the Lambda function uses must have a policy that enables it to invoke this AWS Service from the Lambda function.
To conclude, you can use RedshiftDataClient as opposed to Spring APIs to insert/modify/delete Redshift data from an AWS Lambda function.

java.lang.NoSuchMethodError: com.google.common.base.CharMatcher.whitespace()

I'm writing android unit tests with Robolectric. When I run my tests currently, I keep getting the above error.
I have looked at and tried tons of suggested solutions from here, but none of them have resolved this error.
So far I have looked at the dependency tree and I can see two versions of guava being used:
+--- com.google.guava:guava-jdk5:13.0#jar
+--- com.google.guava:guava:27.0.1-android#jar
After noticing this, I have then tried to:
exclude the first dependency
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:4.0.1'
classpath ('org.robolectric:robolectric:4.1') {
exclude group: 'com.google.guava', module: 'guava-jdk5'
}
}
}
upgrade the guava version to the latest
api 'com.google.guava:guava:27.0.1-android'
This is what the error looks like:
java.lang.NoSuchMethodError: com.google.common.base.CharMatcher.whitespace()Lcom/google/common/base/CharMatcher;
at org.robolectric.res.StringResources.processStringResources(StringResources.java:19)
at org.robolectric.res.StaxValueLoader.onEnd(StaxValueLoader.java:33)
at org.robolectric.res.StaxDocumentLoader.doParse(StaxDocumentLoader.java:66)
at org.robolectric.res.StaxDocumentLoader.loadResourceXmlFile(StaxDocumentLoader.java:30)
at org.robolectric.res.DocumentLoader.loadFile(DocumentLoader.java:48)
at org.robolectric.res.DocumentLoader.load(DocumentLoader.java:27)
at org.robolectric.res.ResourceTableFactory.parseResourceFiles(ResourceTableFactory.java:149)
at org.robolectric.res.ResourceTableFactory.lambda$newFrameworkResourceTable$0(ResourceTableFactory.java:26)
at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:50)
at org.robolectric.res.ResourceTableFactory.newFrameworkResourceTable(ResourceTableFactory.java:12)
at org.robolectric.internal.SdkEnvironment.getSystemResourceTable(SdkEnvironment.java:35)
at org.robolectric.ApkLoader.getSystemResourceTable(ApkLoader.java:32)
at org.robolectric.android.internal.ParallelUniverse.injectResourceStuffForLegacy(ParallelUniverse.java:252)
at org.robolectric.android.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:126)
at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:379)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:252)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:130)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:42)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:84)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
And this is my Test class currently:
#RunWith(RobolectricTestRunner.class)
public class MyTestClass {
MyTestFragment myTestFragment;
#Test
public void fragmentIsNotNull() throws Exception{
myTestFragment = MyTestFragment.newInstance();
assertNotNull(myTestFragment);
}
}
I would appreciate any help with this.
Thanks.
I have finally been able to get this to work by following the answer given here on SO from someone with a similar problem.
The issue was two conflicting guava dependencies as I pointed above.
+--- com.google.guava:guava-jdk5:13.0#jar
+--- com.google.guava:guava:27.0.1-android#jar
This is what I had tried before, to exclude guava,
configurations {
all*.exclude group: 'com.google.guava', module:'guava-jdk5'
}
But the guava-jdk-5 dependency was still being maintained.
So I finally added this to my gradle file instead:
compile('com.google.guava:guava-jdk5:17.0') { force = true }
This is what finally solved the bug.

PowerMock fails with JerseyTest

We're writing unit tests for a Jersey Java REST service using PowerMock. We have to use PowerMock because we use numerous static methods in a legacy system. We're using PowerMock with EasyMock. Whenever we try to inherit from JerseyTest, the whole framework fails.
It's a gradle based project, and the pertinent build.gradle lines are below.
testCompile 'junit:junit:4.12'
testCompile group: 'org.easymock', name: 'easymock', version: '3.5.1'
testCompile group: 'org.easymock', name: 'easymockclassextension', version: '3.2'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.3'
testCompile group: 'org.powermock', name: 'powermock-api-easymock', version: '1.7.3'
We have a few EasyMock unit tests up and running, so we know our imports are working correctly. The problem is that since we're testing a Jersey web service, our unit tests inherit from JerseyTest. Writing a PowerMock unit test without inheriting from JerseyTest works fine. But when we try to inherit from JerseyTest, it all falls apart. Google failed us (apparently no one else who has written a Jersey web service has tried using PowerMock).
What we do is fairly straight-forward. This works:
#RunWith(PowerMockRunner.class)
public class PowerMockTest {
private final static String TARGET = "ourwebservice/";
#Test
public void testConfigurationGet() {
// do stuff, but no Jersey web service calls
}
}
Changing the class declaraction to inherit from JerseyTest, however:
public class PowerMockTest extends JerseyTest {
And we get a complete failure. We're using Eclipse as our IDE, and this is the error that displays in the JUnit window:
initializationError (0.000 s)
The Failure Trace window gives more details:
java.lang.VerifyError: Inconsistent stackmap frames at branch target 38
Exception Details:
Location:
com/ourcompany/ourproduct/rest/PowerMockTest.<init>()V #38: aload_1
Reason:
Type uninitializedThis (current frame, locals[1]) is not assignable to 'com/ourcompany/ourproduct/rest/PowerMockTest' (stack map, locals[1])
Current Frame:
bci: #24
flags: { flagThisUninit }
locals: { uninitializedThis, uninitializedThis, top, 'java/lang/Object' }
stack: { 'java/lang/Object', 'java/lang/Object' }
Stackmap Frame:
bci: #38
flags: { flagThisUninit }
locals: { uninitializedThis, 'com/ourcompany/ourproduct/rest/PowerMockTest' }
stack: { }
Bytecode:
0x0000000: 2a4c 1211 b800 1703 bd00 1912 1ab8 001e
0x0000010: b800 244e 2db2 0028 a500 0e2a 01c0 002a
0x0000020: b700 2ea7 0009 2bb7 0030 0157 a700 0301
0x0000030: 3a05 2ab8 0036 b1
Stackmap Table:
append_frame(#38,Object[#14])
chop_frame(#44,1)
same_frame(#47)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.getTestMethods(PowerMockJUnit44RunnerDelegateImpl.java:109)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.<init>(PowerMockJUnit44RunnerDelegateImpl.java:85)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl.<init>(PowerMockJUnit47RunnerDelegateImpl.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl.<init>(PowerMockJUnit49RunnerDelegateImpl.java:25)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:172)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:48)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:108)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:71)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:36)
at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
We can't even step into the method to debug it; it fails before that (note, the test doesn't even actually do anything yet; we're just trying to get things set up first).
Anyone have any idea what's going on? Do we have some sort of configuration error? Do we have to switch to Mockito?

dosgi: No resource methods have been found for resource class - javax.ws.rs annotation ignored?

i run in an exception showed below.
I tried to publish a webservie using annotation with dosgi. But is looks like the annotations will be ignored.
When i use
restProps.put("service.exported.configs", "org.apache.cxf.ws");
in my Activator.java Class without javax.ws.rs annotations, it works fine and i can request the wsdl (localhost:9090/provalet?wsdl).
Here are some related threads, but non of these answers helped me:
"No resource methods" when using JAX-RS on TomEE+
-> in considered the "public" scope
CXF DOSGi is ignoring annotations
http://cxf.547215.n5.nabble.com/CXF-DOSGi-is-ignoring-JAX-RS-annotations-td4495048.html
-> i have no bundle named "org.apache.servicemix.specs.jsr311-api-1.1"
i also developed this example http://maksim.sorokin.dk/it/2011/09/18/maven-apache-felix-cxf-dosgi-an-example-of-dosgi-service/
-> but same exception
I work with
List item
apache felix 5.4.0
Distributed OSGi Distribution Software Single-Bundle Distribution (1.2.0)
JAVA 1.8
my bundles are:
START LEVEL 1
ID|State |Level|Name
0|Active | 0|System Bundle (5.4.0)
1|Active | 1|backport-util-concurrent (3.1.0)
2|Active | 1|ANTLR Runtime (3.1.3)
3|Active | 1|Apache Commons Bean Utilities (1.8.0)
4|Active | 1|Apache Commons Collections (3.2.1)
5|Active | 1|Apache Commons Logging (1.1.1)
6|Active | 1|Apache Log4J (1.2.15)
7|Active | 1|SLF4J API (1.5.10)
8|Resolved | 1|SLF4J Log4J Binding (1.5.10)
9|Active | 1|Distributed OSGi Distribution Software Single-Bundle Distribution (1.2.0)
10|Active | 1|javax.ws.rs-api (2.0.1)
11|Active | 1|jaxb-api (2.2.7)
12|Active | 1|Sesame 2.1.1 onejar. (2.1.1)
13|Active | 1|Apache Felix Gogo Command (0.8.0)
14|Active | 1|Apache Felix Gogo Runtime (0.8.0)
15|Active | 1|Apache Felix Gogo Shell (0.8.0)
16|Active | 1|osgi.cmpn (4.2.0.200908310645)
17|Active | 1|provalet (1.0.0.SNAPSHOT)
18|Active | 1|Metro Web Services API OSGi Bundle (2.1.0.b16)
19|Active | 1|Prova compact (3.2.1)
Activator.java (OSGi Activator in my bundle provalet (1.0.0.SNAPSHOT)):
public void start(BundleContext arg0) throws Exception {
Activator.arg0 = arg0;
System.out.println("Start Provalet...");
Dictionary<String, String> restProps = new Hashtable<String, String>();
restProps.put("service.exported.interfaces", "*");
restProps.put("service.exported.configs", "org.apache.cxf.rs");
restProps.put("service.exported.intents", "HTTP");
restProps.put("org.apache.cxf.rs.address", "http://localhost:9090/provalet");
arg0.registerService(ProvaletService.class.getName(),
new ProvaletServiceImpl(), restProps);
}
ProvaletService.java:
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#WebService
public interface ProvaletService {
public String greetMe(#WebParam(name = "greeterName") String greeterName);
public String getMetaData();
public String startTestProva();
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/sayhelo")
public String sayHello();
}
OSGI-INF/remote-service/remote-service.xml:
<service-descriptions xmlns="http://www.osgi.org/xmlns/sd/v1.0.0">
<service-description>
<provide interface="de.fuBerlin.api.ProvaletService" />
<property name="service.exported.interfaces">*</property>
<property name="service.exported.configs">org.apache.cxf.rs</property>
<property name="service.exported.intents">HTTP</property>
<property name="org.apache.cxf.rs.address">http://localhost:9090</property>
</service-description>
</service-descriptions>
Here is the part of my pom.xml responsable for generating the bundle
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.2.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Export-Package>
de.fuBerlin.provalet,
de.fuBerlin.api
</Export-Package>
<Import-Package>
org.apache.cxf.dosgi.dsw.qos,
org.osgi.framework;version="1.5.0",
org.osgi.util.tracker;version="1.4.0",
ws.prova.api2;version="3.2.1",
ws.prova.exchange;version="3.2.1",
ws.prova.exchange.impl;version="3.2.1",
ws.prova.service;version="3.2.1",
javax.jws,
javax.ws.rs;version="[2.0,3)",
javax.ws.rs.core;version="[2.0,3)"
</Import-Package>
<Private-Package>
</Private-Package>
<Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
<Bundle-Activator>
de.fuBerlin.provalet.Activator
</Bundle-Activator>
</instructions>
</configuration>
</plugin>
</plugins>
Here is the exception:
application context:org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext#4796c889: display name [OsgiBundleXmlApplicationContext(bundle=cxf-dosgi-ri-singlebundle-distribution, config=classpath:/OSGI-INF/cxf/intents/intent-map.xml)]; startup date [Tue Apr 26 10:18:40 CEST 2016]; root of context hierarchy
retrieved intent map: IntentMap: {addressing=org.apache.cxf.ws.policy.WSPolicyFeature#667a0762, logging=org.apache.cxf.feature.LoggingFeature#353563e5, SOAP=org.apache.cxf.binding.soap.SoapBindingConfiguration#171868d4, SOAP.1_1=org.apache.cxf.binding.soap.SoapBindingConfiguration#171868d4, SOAP.1_2=org.apache.cxf.binding.soap.SoapBindingConfiguration#59a950ae, HTTP=PROVIDED}
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore exportService
INFO: interfaces selected for export: [de.fuBerlin.api.ProvaletService]
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore exportService
INFO: configuration types selected for export: [org.apache.cxf.rs]
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore exportService
INFO: creating initial ExportDescription for interface de.fuBerlin.api.ProvaletService with configuration types [org.apache.cxf.rs]
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore exportService
INFO: creating server for interface de.fuBerlin.api.ProvaletService
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore exportService
INFO: found handler for de.fuBerlin.api.ProvaletService -> org.apache.cxf.dosgi.dsw.handlers.JaxRSPojoConfigurationTypeHandler#4c6b2597
Apr 26, 2016 10:18:40 AM org.apache.cxf.dosgi.dsw.handlers.JaxRSPojoConfigurationTypeHandler createServer
INFO: Creating a de.fuBerlin.api.ProvaletService endpoint via JaxRSPojoConfigurationTypeHandler, address is http://localhost:9090/provalet
Apr 26, 2016 10:18:40 AM org.apache.cxf.jaxrs.utils.ResourceUtils checkMethodDispatcher
WARNING: No resource methods have been found for resource class de.fuBerlin.api.ProvaletService
Apr 26, 2016 10:18:40 AM org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean checkResources
SEVERE: No resource classes found
Exception in thread "pool-6-thread-1" org.apache.cxf.service.factory.ServiceConstructionException
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:122)
at org.apache.cxf.dosgi.dsw.handlers.JaxRSPojoConfigurationTypeHandler.createServer(JaxRSPojoConfigurationTypeHandler.java:135)
at org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore.exportService(RemoteServiceAdminCore.java:244)
at org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminInstance$1.run(RemoteServiceAdminInstance.java:78)
at org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminInstance$1.run(RemoteServiceAdminInstance.java:71)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminInstance.exportService(RemoteServiceAdminInstance.java:71)
at org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminInstance.exportService(RemoteServiceAdminInstance.java:40)
at org.apache.cxf.dosgi.topologymanager.TopologyManager$2.run(TopologyManager.java:254)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ws.rs.WebApplicationException
at org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean.checkResources(AbstractJAXRSFactoryBean.java:238)
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:85)
... 11 more
Assumption: I even think that is a problem with dependencies and it looks like the javax.ws.rs annotation will be ignored. Maybe i have a mistake with the bundle versions either.
Does someone know something more about this problem and how i can solve this?
Please let me know, if you need more information.
kind regards
lars
okay..
a working targetplatform looks like this.. it was indeed a problem with dependencies.
START LEVEL 1
ID|State |Level|Name
0|Active | 0|System Bundle (5.4.0)
1|Active | 1|backport-util-concurrent (3.1.0)
2|Active | 1|ANTLR Runtime (3.1.3)
3|Active | 1|Apache Commons Bean Utilities (1.8.0)
4|Active | 1|Apache Commons Collections (3.2.1)
5|Active | 1|Apache Commons Logging (1.1.1)
6|Active | 1|Apache Log4J (1.2.15)
7|Active | 1|SLF4J API (1.5.10)
8|Resolved | 1|SLF4J Log4J Binding (1.5.10)
9|Active | 1|Distributed OSGi Distribution Software Single-Bundle Distribution (1.2.0)
10|Active | 1|jaxb-api (2.2.7)
11|Active | 1|Sesame 2.1.1 onejar. (2.1.1)
12|Active | 1|Apache Felix Gogo Command (0.8.0)
13|Active | 1|Apache Felix Gogo Runtime (0.8.0)
14|Active | 1|Apache Felix Gogo Shell (0.8.0)
15|Active | 1|Apache ServiceMix :: Specs :: JSR-311 API 1.0 (2.7.0)
16|Active | 1|osgi.cmpn (4.2.0.200908310645)
17|Active | 1|provalet (1.0.0.SNAPSHOT)
18|Active | 1|Metro Web Services API OSGi Bundle (2.1.0.b16)
19|Active | 1|Prova compact (3.2.1)
kind regards and hope other user will work easier with that.

Grails Unit Test Exception java.lang.Exception: No tests found matching grails test target pattern filter

I am just starting to learn Grails testing and I tried to write my first grails test.For this, I created a fresh grails project and created a controller named com.rahulserver.SomeController:
package com.rahulserver
class SomeController {
def index() { }
def someAction(){
}
}
When I created this controller, grails automatically created a com.rahulserver.SomeControllerSpec under test/unit folder.
Here is my SomeControllerSpec.groovy:
package com.rahulserver
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* See the API for {#link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
#TestFor(SomeController)
class SomeControllerSpec extends Specification {
def setup() {
}
def cleanup() {
}
void testSomeAction() {
assert 1==1
}
}
When I right click this class, and run this test, I get following:
Testing started at 5:21 PM ...
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to test
....................................
|Running without daemon...
..........................................
|Compiling 1 source files
.
|Running 1 unit test...|Running 1 unit test... 1 of 1
--Output from initializationError--
Failure: |
initializationError(org.junit.runner.manipulation.Filter)
|
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
|Completed 1 unit test, 1 failed in 0m 0s
.Tests FAILED
|
- view reports in D:\115Labs\grailsunittestdemo\target\test-reports
Error |
Forked Grails VM exited with error
Process finished with exit code 1
So why is it failing?
EDIT
I am using grails 2.4.3
The unit tests are defined with Spock by default:
void testSomeAction() {
assert 1==1
}
Should be written as:
void "Test some action"() {
expect:
1==1
}
See http://spockframework.github.io/spock/docs/1.0/index.html