AspectJ execution pointcut on same method throwing NPE [duplicate] - aspectj

I have 2 aspects that are applied on the same method.
When the method executes correctly I have no problem, everything is working fine and both aspects work as expected.
The problem is when the method throw an exception. In these cases, the first aspect re-throw correctly the exception, but the second aspect is generating a nullpointerexception.
I was able to reproduce the problem isolating the case on a unit test in a separated project.
Those are the aspects (actually I removed all the logic, at the moment they do nothing):
#Aspect
public class LogContextConstantAspect {
#Around("execution(* *(..)) && #annotation(logContextConstant)")
public Object aroundMethod(ProceedingJoinPoint joinPoint, LogContextConstant logContextConstant) throws Throwable {
try {
Object res = joinPoint.proceed();
return res;
} catch (Throwable e) {
throw e;
}
}
}
and
#Aspect
public class LogExecutionTimeAspect {
#Around("execution(* *(..)) && #annotation(logExecutionTime)")
public Object around(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {
try {
Object res = joinPoint.proceed();
return res;
} catch (Throwable e) {
throw e;
}
}
}
while those are the 2 custom annotation that I implemented
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface LogExecutionTime {
String paramKey() default "execution_time";
}
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
#Documented
public #interface LogContextConstant {
String name();
String value();
}
then I created a simple class with the following methods
public class AspectSimple {
public int execute() {
System.out.println("ok");
return 1;
}
public int failSimple() throws CustomException {
throw new CustomException("ko");
}
#LogExecutionTime
public int failWithAspect1() throws CustomException {
throw new CustomException("ko");
}
#LogContextConstant(name="test", value = "test")
public int failWithAspect2() throws CustomException {
throw new CustomException("ko");
}
#LogExecutionTime
#LogContextConstant(name="test", value = "test")
public int executeWithAspect() {
return 1;
}
#LogExecutionTime
#LogContextConstant(name="test", value = "test")
public int failWithAspect3() throws CustomException {
throw new CustomException("ko");
}
}
and finally this unit test
public class TestSample {
static AspectSimple as = null;
#BeforeAll
public static void setup() {
as = new AspectSimple();
}
#Test
public void test1() {
int res = as.execute();
assertEquals(1, res);
}
#Test
public void test2() {
int res = as.executeWithAspect();
assertEquals(1, res);
}
#Test
public void test3() {
try {
int res = as.failSimple();
} catch (CustomException e) {
assertNotNull(e);
} catch (Exception e) {
fail();
}
}
#Test
public void test4() {
try {
int res = as.failWithAspect1();
} catch (CustomException e) {
assertNotNull(e);
} catch (Exception e) {
fail();
}
}
#Test
public void test5() {
try {
int res = as.failWithAspect2();
} catch (CustomException e) {
assertNotNull(e);
} catch (Exception e) {
fail();
}
}
#Test
public void test6() {
try {
int res = as.failWithAspect3();
} catch (CustomException e) {
assertNotNull(e);
} catch (Exception e) {
fail();
}
}
}
All tests are running correctly, only the last one (test6) fails.
the application is running on java 8, with aspectj 1.9.4 and junit 5.
Here the complete pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.pivimarco.samples.aspects</groupId>
<artifactId>aspect-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
org.baeldung.executable.ExecutableMavenJar
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<executions>
<execution>
<id>default-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>**/Test*.java</include>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
<include>**/*TestCase.java</include>
</includes>
<properties>
<excludeTags>slow</excludeTags>
</properties>
<forkCount>1</forkCount>
<reuseForks>false</reuseForks>
</configuration>
</execution>
</executions>
<configuration>
<includes>
<include>**/Test*.java</include>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
<include>**/*TestCase.java</include>
</includes>
<properties>
<excludeTags>slow</excludeTags>
</properties>
<forkCount>1</forkCount>
<reuseForks>false</reuseForks>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.11</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.4</version>
<scope>compile</scope>
</dependency>
</dependencies>
<configuration>
<source>1.8</source>
<target>1.8</target>
<proc>none</proc>
<complianceLevel>1.8</complianceLevel>
</configuration>
</plugin>
</plugins>
</build>
</project>
If I apply just a single aspect the CustomException is throwed as aspected,
but when both aspects are applied I'm getting a nullpointerexception.
I've also tried to declare the precedence of the aspects, using DeclarePrecedence annotation, but it didn't work
#DeclarePrecedence("it.pivimarco.samples.aspects.LogContextConstantAspect,it.pivimarco.samples.aspects.LogExecutionTimeAspect")
This is the stacktrace of the NPE
java.lang.NullPointerException
at it.pivimarco.samples.aspects.AspectSimple.failWithAspect3_aroundBody10(AspectSimple.java:35)
at it.pivimarco.samples.aspects.AspectSimple$AjcClosure11.run(AspectSimple.java:1)
at org.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:170)
at it.pivimarco.samples.aspects.LogContextConstantAspect.aroundMethod(LogContextConstantAspect.java:18)
at it.pivimarco.samples.aspects.AspectSimple.failWithAspect3(AspectSimple.java:35)
at it.pivimarco.samples.aspects.TestSample.test6(TestSample.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)

I think you uncovered a bug in the AspectJ compiler (versions 1.9.3, 1.9.4) which does not occur in version 1.9.2, as I said in my comment. I have just created AspectJ bug ticket #552687 on your behalf. Please check there for further updates. For now you can just downgrade to 1.9.2 and continue working.
Update: AspectJ 1.9.5 with the bugfix is out. Please try again. My retest was successful.

Related

It says status":500,"error":"Internal Server Error on soapui when I request for a response

This endpoint class
correlate the methods from request and response classes from the target as I put the request and response classes in target directory.
package com.security.test;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import security.test.GetTestRequest;
import security.test.GetTestResponse;
#Endpoint
public class TestEndpoint {
private final String NAMESPACE_URI="http://security/test";
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getTestRequest")
#ResponsePayload
public GetTestResponse securityResponse(#RequestPayload GetTestRequest request){
GetTestResponse response = new GetTestResponse();
String given=request.getGivenString();
int myAge=given.length();
response.setLength(myAge);
System.out.println(response);
return response;
}
}
All the dependencies from pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.security</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>18</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
<exclusion>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.5.0</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>${project.basedir}/src/main/resources/test.xsd</source>
</sources>
</configuration>
</plugin>
</plugins>
</build>
</project>
using xwsInterceptor it intercept the request and looks for authentication using simple passwordvalidationCallHandler
This webSConfig class extends WsConfigurerAdapter
{
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "test")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema testSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("TestPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://security/test");
wsdl11Definition.setSchema(testSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema testSchema() {
return new SimpleXsdSchema(new ClassPathResource("test.xsd"));
}
#Bean
public XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Bean
public CallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsersMap(Collections.singletonMap("admin", "pwd123"));
return callbackHandler;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(securityInterceptor());
}
}
however, I am not getting the right response,It even does not response about the security issue it responses status":500,"error":"Internal Server Error on soapUi while I run the request. and the intellij response as
java.lang.IllegalAccessError: class com.sun.xml.wss.impl.SecurableSoapMessage (in unnamed module #0x60285225) cannot access class com.sun.org.apache.xml.internal.security.Init (in module java.xml.crypto) because module java.xml.crypto does not export com.sun.org.apache.xml.internal.security to unnamed module #0x60285225

Not able to generate querydsl Q classes with Azure CosmosDB because #Entity annotation is not present

I am just trying to do a POC using spring boot data jpa along with Azure CosmosDB and query dsl. My plugin in pom.xml looks like this where I am using com.querydsl.apt.jpa.JPAAnnotationProcessor Annotation processor which is supposed to scan files with #Entity Annotaion But in my case Entity class is annotated with #Container instead of #Entity And because of that querdsl is unable to generate Q files. I am wondering is there a way to do it with #Container annotated class?
Pluggin in pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.5.6
com.configuration
Pagination-and-filtering
0.0.1-SNAPSHOT
Pagination-and-filtering
Demo project for Spring Boot
<java.version>11</java.version>
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-jpa -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
My entity class
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;
private String profession;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
Well according to the documentation, you might be able to achieve this using 2 options:
Option 1: querydsl.unknownAsEmbeddable
set where unknown non-annotated classes should be treated as
embeddable (default: false)
https://querydsl.com/static/querydsl/3.1.2.BUILD/reference/html/ch03s03.html
Example of Usage:
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
<options>
<querydsl.entityAccessors>true</querydsl.entityAccessors>
<querydsl.listAccessors>false</querydsl.listAccessors>
<querydsl.useGetters>true</querydsl.useGetters>
<querydsl.unknownAsEmbeddable>true</querydsl.unknownAsEmbeddable>
</options>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
</plugin>
Option 2: Using #QueryEntities(ClassWithContainerAnnotation.class)
https://querydsl.com/static/querydsl/4.4.0/apidocs/com/querydsl/core/annotations/QueryEntities.html
Example package-info.java
#com.querydsl.core.annotations.QueryEntities({com.onescorpin.jpa.AbstractAuditedEntity.class, com.onescorpin.jpa.AbstractAuditedEntityAsMillis.class})
package com.onescorpin.metadata;
Ref: https://github.com/wcandy0088/nova/blob/master/nova-new1/core/operational-metadata/operational-metadata-jpa/src/main/java/com/onescorpin/metadata/package-info.java

NetBeans Junit5 Tests-Output ignore DisplayName Nested-Format

I do not get the names from the annoations "#DisplayName" as a test result in NetBeans. Only the names of the test functions are shown. The grouped display of the nested tests is also ignored.
Source code
#DisplayName("test facade")
public class TestFacadeTest {
#BeforeAll
public static void setUpClass() {
}
#AfterAll
public static void tearDownClass() {
}
#BeforeEach
public void setUp() {
}
#AfterEach
public void tearDown() {
}
#Test
#DisplayName("senseless test")
public void test(){
Assertions.assertTrue(true);
}
#Nested
#DisplayName("tests - compareStringNullSave")
class CompateStringNullSaveTestGroup {
#BeforeEach
public void setUp() {
}
#Test
#DisplayName("both identical")
public void Test1(){
String str1 = "Test123";
String str2 = "Test123";
Assertions.assertTrue(TestFacade.compareStringNullSave(str1, str2));
Assertions.assertTrue(TestFacade.compareStringNullSave(str2, str1));
}
#Test
#DisplayName("Identical text but different uppercase and lowercase letters")
public void Test2(){
String str1 = "Test123";
String str2 = "test123";
Assertions.assertFalse(TestFacade.compareStringNullSave(str1, str2));
Assertions.assertFalse(TestFacade.compareStringNullSave(str2, str1));
}
}
}
Extract from the pom.xml
<dependencies>
[...]
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
[...]
</dependencies>
<build>
<plugins>
[...]
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<properties>
<configurationParameters>
junit.jupiter.conditions.deactivate = *
junit.jupiter.extensions.autodetection.enabled = true
junit.jupiter.testinstance.lifecycle.default = per_class
</configurationParameters>
</properties>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
What do I have to set so that the test display in NetBeans shows the DisplayNames and uses the nested grouping?
NetBeans version: 12.0
Java version: 11 (OpenJDK)
Maven added support for the #Display annotation in the 3.0.0.0-M4 version of the surefire plugin. Also, you need to configure the parameters of statelessTestsetReporter and statelessTestsetInfoReporter extensions to allow for NetBeans to match display names correctly.
So currently (01.2021), you can use 3.0.0.0-M4 or newer versions of the surefire plugin, and the version of JUnit should be more than 5.5.2. Something like that should work:
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<statelessTestsetReporter implementation="org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter">
<version>3.0</version>
<usePhrasedFileName>true</usePhrasedFileName>
<usePhrasedTestSuiteClassName>true</usePhrasedTestSuiteClassName>
<usePhrasedTestCaseClassName>true</usePhrasedTestCaseClassName>
<usePhrasedTestCaseMethodName>true</usePhrasedTestCaseMethodName>
</statelessTestsetReporter>
<statelessTestsetInfoReporter implementation="org.apache.maven.plugin.surefire.extensions.junit5.JUnit5StatelessTestsetInfoReporter">
<usePhrasedClassNameInRunning>true</usePhrasedClassNameInRunning>
</statelessTestsetInfoReporter>
<properties>
<configurationParameters>
junit.jupiter.conditions.deactivate = *
junit.jupiter.extensions.autodetection.enabled = true
junit.jupiter.testinstance.lifecycle.default = per_class
</configurationParameters>
</properties>
</configuration>
</plugin>
</plugins>
Here how it looks in my case:
#DisplayName("Display Name of class")
public class testClassSimple {
#Test
#DisplayName("Display name of method 1")
public void testMethod1() {
}
#Test
#DisplayName("Display name of method 2")
public void testMethod2() {
}
}
As for nested grouping and the #Nested annotation, currently, NetBeans doesn't support nested grouping of test results in the test result window. Probably it's better to use different classes for such tests instead of nested classes.

initializationError in Eclipse when #PrepareForTest is at method but at class

Small example, using jUnit 4.11, Mockito 2.6.3, PowerMock 1.7.0RC4:
public class TheClass {
public static int giveMeNumber() {
return 70;
}
public static int giveMeThatNumber(int it) {
return it;
}
}
and
import org.junit.Test;
import org.junit.runner.*;
import org.mockito.*;
import org.powermock.api.mockito.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
// #PrepareForTest(TheClass.class)
public class TheTestClass {
#Test
#PrepareForTest(TheClass.class)
public void test1() {
PowerMockito.mockStatic(TheClass.class);
Mockito.when(TheClass.giveMeNumber()).thenReturn(13);
System.out.println(TheClass.giveMeNumber());
}
#Test
#PrepareForTest(TheClass.class)
public void test2() {
PowerMockito.mockStatic(TheClass.class);
Mockito.when(TheClass.giveMeThatNumber(25)).thenReturn(50);
System.out.println(TheClass.giveMeThatNumber(25));
}
#Test
public void test3() {
System.out.println("Hey, I do not want a #Prepare...d class!");
}
}
The dependencies are loaded with Maven, the pom.xml is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow.bowi</groupId>
<artifactId>place.of.prepareForTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Place of PrepareForTest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<powermock.version>1.7.0RC4</powermock.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.6.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
When I run those tests in eclipse (right click at class name, Run as..., JUnit test), they pass (not actually checking anything, I know :-) ). When I run them alone (right click at method name, Run as..., JUnit test), they fail with an initializationError [Runner: JUnit 4] (0,000s) without any trace.
Strangely, when I remove the #PrepareForTest(TheClass.class) from the method signatures and uncomment it in the class signature, all three run fine both together and alone.
But now look: test3() says it does not want a "prepared" TheClass. What I thought was correct, is to move the #PrepareForTest(TheClass.class) from the class signature to the signatures of the methods that need it (test1() and test2()), like it was before but failed.
What am I doing wrong?

Insert in MongoDB with Spring backend issue?

I used to insert data into a MongoDB database and i faced some problems; here is my main.java
#SpringBootApplication
public class Application {
public static final String DB_NAME = "test";
public static final String USERS_COLLECTION = "users";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
try {
MongoClient mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
Test2 p = new Test2("jon");
mongoOps.insert(p, USERS_COLLECTION);
mongo.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}}
Here is my entity:
#Document
public class Test2 extends DomainBase {
/**
*
*/
private static final long serialVersionUID = -1866079511424097005L;
private Long Id;
private String mail;
public Test2() {
super();
}
public Test2(String mail) {
this.setMail(mail);
}
#Id
#Field("id")
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
And here is my repository:
public interface Test2Repo extends MongoRepository<Test2, Long> {
}
I think it is well done for this part but it keep showing me the same following errors :
2016-03-09 15:05:02.194 INFO 19429 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/home/no-one/workspace/skilify-core/target/classes/, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-actuator/1.3.2.RELEASE/spring-boot-starter-actuator-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter/1.3.2.RELEASE/spring-boot-starter-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot/1.3.2.RELEASE/spring-boot-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.3.2.RELEASE/spring-boot-autoconfigure-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.3.2.RELEASE/spring-boot-starter-logging-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar, file:/home/no-one/.m2/repository/ch/qos/logback/logback-core/1.1.3/logback-core-1.1.3.jar, file:/home/no-one/.m2/repository/org/slf4j/jul-to-slf4j/1.7.13/jul-to-slf4j-1.7.13.jar, file:/home/no-one/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.13/log4j-over-slf4j-1.7.13.jar, file:/home/no-one/.m2/repository/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-actuator/1.3.2.RELEASE/spring-boot-actuator-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.3.2.RELEASE/spring-boot-starter-data-jpa-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.3.2.RELEASE/spring-boot-starter-aop-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/aspectj/aspectjweaver/1.8.8/aspectjweaver-1.8.8.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.3.2.RELEASE/spring-boot-starter-jdbc-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.0.30/tomcat-jdbc-8.0.30.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/tomcat-juli/8.0.30/tomcat-juli-8.0.30.jar, file:/home/no-one/.m2/repository/org/springframework/spring-jdbc/4.2.4.RELEASE/spring-jdbc-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.11.Final/hibernate-entitymanager-4.3.11.Final.jar, file:/home/no-one/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/home/no-one/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar, file:/home/no-one/.m2/repository/org/hibernate/hibernate-core/4.3.11.Final/hibernate-core-4.3.11.Final.jar, file:/home/no-one/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/home/no-one/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar, file:/home/no-one/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/home/no-one/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/home/no-one/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.5.Final/hibernate-commons-annotations-4.0.5.Final.jar, file:/home/no-one/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/home/no-one/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/home/no-one/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar, file:/home/no-one/.m2/repository/org/springframework/data/spring-data-jpa/1.9.2.RELEASE/spring-data-jpa-1.9.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-orm/4.2.4.RELEASE/spring-orm-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-aspects/4.2.4.RELEASE/spring-aspects-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-security/1.3.2.RELEASE/spring-boot-starter-security-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-aop/4.2.4.RELEASE/spring-aop-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/home/no-one/.m2/repository/org/springframework/security/spring-security-config/4.0.3.RELEASE/spring-security-config-4.0.3.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/security/spring-security-core/4.0.3.RELEASE/spring-security-core-4.0.3.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/security/spring-security-web/4.0.3.RELEASE/spring-security-web-4.0.3.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-core/4.2.4.RELEASE/spring-core-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.3.2.RELEASE/spring-boot-starter-web-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.3.2.RELEASE/spring-boot-starter-tomcat-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.0.30/tomcat-embed-core-8.0.30.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.0.30/tomcat-embed-el-8.0.30.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/embed/tomcat-embed-logging-juli/8.0.30/tomcat-embed-logging-juli-8.0.30.jar, file:/home/no-one/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.0.30/tomcat-embed-websocket-8.0.30.jar, file:/home/no-one/.m2/repository/org/springframework/boot/spring-boot-starter-validation/1.3.2.RELEASE/spring-boot-starter-validation-1.3.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/hibernate/hibernate-validator/5.2.2.Final/hibernate-validator-5.2.2.Final.jar, file:/home/no-one/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/home/no-one/.m2/repository/com/fasterxml/classmate/1.1.0/classmate-1.1.0.jar, file:/home/no-one/.m2/repository/org/springframework/spring-web/4.2.4.RELEASE/spring-web-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-webmvc/4.2.4.RELEASE/spring-webmvc-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/mobile/spring-mobile-device/1.1.5.RELEASE/spring-mobile-device-1.1.5.RELEASE.jar, file:/home/no-one/.m2/repository/io/jsonwebtoken/jjwt/0.4/jjwt-0.4.jar, file:/home/no-one/.m2/repository/org/slf4j/slf4j-api/1.7.13/slf4j-api-1.7.13.jar, file:/home/no-one/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.5.3/jackson-databind-2.5.3.jar, file:/home/no-one/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.5.3/jackson-annotations-2.5.3.jar, file:/home/no-one/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.5.3/jackson-core-2.5.3.jar, file:/home/no-one/.m2/repository/com/h2database/h2/1.4.188/h2-1.4.188.jar, file:/home/no-one/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar, file:/home/no-one/.m2/repository/org/springframework/data/spring-data-mongodb/1.4.1.RELEASE/spring-data-mongodb-1.4.1.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-tx/4.2.4.RELEASE/spring-tx-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-context/4.2.4.RELEASE/spring-context-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-beans/4.2.4.RELEASE/spring-beans-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/spring-expression/4.2.4.RELEASE/spring-expression-4.2.4.RELEASE.jar, file:/home/no-one/.m2/repository/org/springframework/data/spring-data-commons/1.11.2.RELEASE/spring-data-commons-1.11.2.RELEASE.jar, file:/home/no-one/.m2/repository/org/mongodb/mongo-java-driver/2.13.3/mongo-java-driver-2.13.3.jar, file:/home/no-one/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.13/jcl-over-slf4j-1.7.13.jar]
I do not know in which part or where the problem really reside, for better analysis here is the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Application information -->
<groupId>**</groupId>
<artifactId>**</artifactId>
<version>1.0-SNAPSHOT</version>
<name>**</name>
<url>**</url>
<inceptionYear>**</inceptionYear>
<!-- Properties information -->
<properties>
<java.version>1.7</java.version>
<spring-boot.version>1.2.3.RELEASE</spring-boot.version>
<spring-framework.version>4.1.6.RELEASE</spring-framework.version>
<jjwt.version>0.4</jjwt.version>
<h2.version>1.4.188</h2.version>
<jackson.version>2.5.3</jackson.version>
<apache-commons.version>3.0</apache-commons.version>
<junit.version>4.12</junit.version>
<jacoco-maven-plugin.version>0.7.5.201505241946</jacoco-maven-plugin.version>
<coveralls-maven-plugin.version>4.1.0</coveralls-maven-plugin.version>
<jongo.version>1.1</jongo.version>
<mongodb-driver.version>2.13.0</mongodb-driver.version>
</properties>
<!-- Parent information -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<!-- Dependency information -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<!-- <dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongodb-driver.version}</version>
</dependency>
<dependency>
<groupId>org.jongo</groupId>
<artifactId>jongo</artifactId>
<version>${jongo.version}</version>
</dependency> -->
</dependencies>
<!-- Build information -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>${coveralls-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>
Please could you help me ?
After all I had to remove the version of the spring-data-mongodb dependency in the pom.xml to fix it since it was showing a warning; so it became :
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>