Cucumber: no backend found when running from Spring Boot jar - maven

I am creating a small testing framework that should utilize both Cucumber and the Spring Boot platform. The idea is to let the whole application be packaged as a single jar and run after the BDD features have been properly parametrized.
The framework starts in command line runner mode like this:
public class FwApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(FwApplication.class, args);
}
#Override
public void run(String... arg0) throws Exception {
JUnitCore.main(CucumberIntegration.class.getCanonicalName());
}
}
Then there is the CucumberIntegration class:
#RunWith(Cucumber.class)
#CucumberOptions(features = "config/features")
#ContextConfiguration(classes= AppConfiguration.class)
public class CucumberIntegration {
}
I have also some simple tests which run fine under my IDE, but when I try to package the application and run it over java -jar fw-0.0.1-SNAPSHOT.jar I get to see following:
There was 1 failure:
1) initializationError(com.fmr.bddfw.test.CucumberIntegration)
cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
at cucumber.runtime.Runtime.<init>(Runtime.java:81)
at cucumber.runtime.Runtime.<init>(Runtime.java:70)
(...)
All necessary jars are already in the one jar created by maven and it works fine under my IDE.
Any ideas what could help?
EDIT: Here my pom file.
<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>com.xxx</groupId>
<artifactId>fw</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>fw</name>
<description>BDD Testing Framework</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<cucumber.version>1.2.5</cucumber.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Using the suggestion given by Marcus:
Step1: Create your custom MultiLoader class:
package cucumber.runtime.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
public class CustomMultiLoader implements ResourceLoader {
public static final String CLASSPATH_SCHEME = "classpath*:";
public static final String CLASSPATH_SCHEME_TO_REPLACE = "classpath:";
private final ClasspathResourceLoader classpath;
private final FileResourceLoader fs;
public CustomMultiLoader(ClassLoader classLoader) {
classpath = new ClasspathResourceLoader(classLoader);
fs = new FileResourceLoader();
}
#Override
public Iterable<Resource> resources(String path, String suffix) {
if (isClasspathPath(path)) {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String locationPattern = path.replace(CLASSPATH_SCHEME_TO_REPLACE, CLASSPATH_SCHEME) + "/**/*" + suffix;
org.springframework.core.io.Resource[] resources;
try {
resources = resolver.getResources(locationPattern);
} catch (IOException e) {
resources = null;
e.printStackTrace();
}
return convertToCucumberIterator(resources);
} else {
return fs.resources(path, suffix);
}
}
private Iterable<Resource> convertToCucumberIterator(org.springframework.core.io.Resource[] resources) {
List<Resource> results = new ArrayList<Resource>();
for (org.springframework.core.io.Resource resource : resources) {
results.add(new ResourceAdapter(resource));
}
return results;
}
public static String packageName(String gluePath) {
if (isClasspathPath(gluePath)) {
gluePath = stripClasspathPrefix(gluePath);
}
return gluePath.replace('/', '.').replace('\\', '.');
}
private static boolean isClasspathPath(String path) {
if (path.startsWith(CLASSPATH_SCHEME_TO_REPLACE)) {
path = path.replace(CLASSPATH_SCHEME_TO_REPLACE, CLASSPATH_SCHEME);
}
return path.startsWith(CLASSPATH_SCHEME);
}
private static String stripClasspathPrefix(String path) {
if (path.startsWith(CLASSPATH_SCHEME_TO_REPLACE)) {
path = path.replace(CLASSPATH_SCHEME_TO_REPLACE, CLASSPATH_SCHEME);
}
return path.substring(CLASSPATH_SCHEME.length());
}
}
Step2: Create an adapter between org.springframework.core.io.Resource and cucumber.runtime.io.Resource:
package cucumber.runtime.io;
import java.io.IOException;
import java.io.InputStream;
public class ResourceAdapter implements Resource {
org.springframework.core.io.Resource springResource;
public ResourceAdapter(org.springframework.core.io.Resource springResource) {
this.springResource = springResource;
}
public String getPath() {
try {
return springResource.getFile().getPath();
} catch (IOException e) {
try {
return springResource.getURL().toString();
} catch (IOException e1) {
e1.printStackTrace();
return "";
}
}
}
public String getAbsolutePath() {
try {
return springResource.getFile().getAbsolutePath();
} catch (IOException e) {
return null;
}
}
public InputStream getInputStream() throws IOException {
return this.springResource.getInputStream();
}
public String getClassName(String extension) {
String path = this.getPath();
if (path.startsWith("jar:")) {
path = path.substring(path.lastIndexOf("!") + 2);
return path.substring(0, path.length() - extension.length()).replace('/', '.');
} else {
path = path.substring(path.lastIndexOf("classes") + 8);
return path.substring(0, path.length() - extension.length()).replace('\\', '.');
}
}
}
Step3: Create your custom main class that uses your CustomMultiLoader:
package cucumber.runtime.io;
import static java.util.Arrays.asList;
import java.io.IOException;
import java.util.ArrayList;
import cucumber.runtime.ClassFinder;
import cucumber.runtime.Runtime;
import cucumber.runtime.RuntimeOptions;
public class CucumberStaticRunner {
public static void startTests(String[] argv) throws Throwable {
byte exitstatus = run(argv, Thread.currentThread().getContextClassLoader());
System.exit(exitstatus);
}
public static byte run(String[] argv, ClassLoader classLoader) throws IOException {
RuntimeOptions runtimeOptions = new RuntimeOptions(new ArrayList<String>(asList(argv)));
ResourceLoader resourceLoader = new CustomMultiLoader(classLoader);
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
Runtime runtime = new Runtime(resourceLoader, classFinder, classLoader, runtimeOptions);
runtime.run();
return runtime.exitStatus();
}
}
Step4: Call your custom main class instead of cucumber.api.cli.Main.main:
String[] cucumberOptions = { "--glue", "my.test.pack", "--no-dry-run", "--monochrome", "classpath:features" };
CucumberStaticRunner.startTests(cucumberOptions);

Fixed it by following configuration:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<requiresUnpack>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>

You should add cucumber-java dependency
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>

private static byte run(String[] argv, ClassLoader classLoader) throws IOException {
// cucumber/Spring Boot classloader problem
// CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH
RuntimeOptions runtimeOptions = new RuntimeOptions(new ArrayList<String>(asList(argv)));
ResourceLoader resourceLoader = new MultiLoader(classLoader);
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
Reflections reflections = new Reflections(classFinder);
List<Backend> list = new ArrayList<>();
list.addAll(reflections.instantiateSubclasses(Backend.class, "cucumber.runtime", new Class[]{ResourceLoader.class}, new Object[]{resourceLoader}));
if (list.size() == 0) {
JavaBackend javaBackend = new JavaBackend(resourceLoader);
list.add(javaBackend);
}
Runtime runtime = new Runtime(resourceLoader, classLoader, list, runtimeOptions);
runtime.run();
return runtime.exitStatus();
}

I used below code in POM.xml file
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
It is working fine now.

Related

Simple Aspect not Executing

I had this Aspect working then all of a sudden it stopped. #AfterThrowing all classes in and below the pointcut. You can see I added a constructor to the Aspect to ensure it is picked up by Spring and it is. Below is a class that I stepped through and watched exceptions thrown and handled. Just throwing (no pun intended) this out there to see if any one notices something.
package mil.ndms.taabatch.af.batchjobs.afdaily.difmsjon;
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.transform.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import mil.ndms.taabatch.af.batchjobs._jobscommon.FileUtilities;
import mil.ndms.taabatch.af.customexceptions.StepException;
#Service
public class DIFMSJonReader implements ItemReader<DIFMSJonModel>, StepExecutionListener
{
private int nextItemIndex;
private List<DIFMSJonModel> difmsJonModelList;
private StepExecution stepExecutionForRead;
#Autowired
FileUtilities fileUtilities;
#Override
/*
* This code in the beforeStep method is required here because this is a custom ItemReader.
* Custom readers need to produce their own list to be iterated over.
* Each item in the List invokes the read method.
*/
public void beforeStep(StepExecution stepExecution)
{
// Initialize Class variables
stepExecutionForRead = stepExecution;
difmsJonModelList = new ArrayList<DIFMSJonModel>();
nextItemIndex = 0;
// Create Flat File Reader
FlatFileItemReader<DIFMSJonModel> reader = null;
try
{
// Get the file location from the BATCH_FILE_PARAMETERS Table
String fileName = fileUtilities.getFileInputLocation("MS204D01.DAT");
// Throw Exception if the location is not found
if(null == fileName)
throw new StepException("File - MS204D01 - Does not exist");
// Build the Flat FileRreader based on the following parameters
reader =
new FlatFileItemReaderBuilder<DIFMSJonModel>()
.name("DIFMSJonReader").linesToSkip(0)
.resource(new FileSystemResource(fileName))
.fixedLength()
.columns(new Range[] { new Range(1, 12), new Range(13, 13), new Range(14, 14), new Range(15, 21) })
.names(new String[] { "jon", "completeIndicator", "laborValid", "jonOpenDate" })
.targetType(DIFMSJonModel.class)
.build();
// Open the file/reader assign it to a context
reader.open(new ExecutionContext());
// Iterate over the open file. Each row will be assigned to a new instance of DIFMSJonModel
// and then stored in the difmsJonModelList
DIFMSJonModel item;
while ((item = (DIFMSJonModel) reader.read()) != null)
{
difmsJonModelList.add(item);
}
}
catch (Exception e)
{
// if this exception is not of type StepException and since we are in a Job Step,
// we are going to add a StepExecution to the Exception to be used by the Aspect which will
// log the exception
if(!(e instanceof StepException))
{
StepException se = new StepException(e);
se.setStepExecution(stepExecution);
e.addSuppressed(new StepException(e));
}
else
{
((StepException) e).setStepExecution(stepExecution);
}
// We must empty the List so that the read() has nothing to read
// This is how we stop the Job
difmsJonModelList.clear();
stepExecution.getJobExecution().setStatus(BatchStatus.FAILED);
}
finally
{
// Close the reader/file
if(null != reader) reader.close();
}
}
#Override
public DIFMSJonModel read()
throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException
{
DIFMSJonModel nextItem = null;
try
{
/* Counter **********************************************************************
* This code is necessary because this is a custom ItemReader.
* This "counter" lets us know which item is next to retrieve from the list.
* Once this method ends the item is passed to the ItemProcessor method
*/
if (nextItemIndex < difmsJonModelList.size())
{
nextItem = difmsJonModelList.get(nextItemIndex);
nextItemIndex++;
}
else
{
nextItemIndex = 0;
}
/* Counter **********************************************************************/
}
catch (Exception e)
{
if(!(e instanceof StepException))
{
StepException se = new StepException(e);
se.setStepExecution(stepExecutionForRead);
e.addSuppressed(se);
}
else
{
((StepException) e).setStepExecution(stepExecutionForRead);
}
// After we process an Exception we must throw the Exception.
// Spring Batch sees the Exception and stops the Job
throw e;
}
return nextItem;
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) { return stepExecution.getExitStatus(); }
}
package mil.ndms.taabatch.af.aspects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import mil.ndms.taabatch.af.customexceptions.StepException;
#Aspect
#Configuration
public class ExcepetionAspect
{
public ExcepetionAspect()
{
System.out.println("");
System.out.println("This is the Aspect");
System.out.println("");
}
#AfterThrowing(pointcut = "execution(* mil.ndms.taabatch.af.batchjobs..*.*(..))", throwing = "e")
public void logException(JoinPoint jp, Throwable e) throws Throwable
{
String name = e.getClass().toString().substring(e.getClass().toString().lastIndexOf(".")+1);
switch(name)
{
case "Exception":
{
Throwable[] se = e.getSuppressed();
StepException exception = (null != se && null != se[0] && se[0] instanceof StepException)
? null : (StepException) se[0];
if(null != exception) logStepException(jp, exception); else logOtherException(jp, e);
}
case "StepException": logStepException(jp, (StepException) e);
default: logOtherException(jp, e);
}
}
private void logStepException(JoinPoint joinPoint, StepException e )
{
final Signature signature = joinPoint.getSignature();
final Class<?> clazz = signature.getDeclaringType();
final Logger logger = LoggerFactory.getLogger(clazz);
logger.error("The following Step has errors - " + "[step-name:{}]", e.getStepExecution().getStepName());
e.getStepExecution().getFailureExceptions().forEach(th -> logger.error(th.getMessage()));
return;
}
private void logOtherException(JoinPoint joinPoint, Throwable e )
{
final Signature signature = joinPoint.getSignature();
final Class<?> clazz = signature.getDeclaringType();
final Logger logger = LoggerFactory.getLogger(clazz);
logger.error(e.getMessage());
return;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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.6.5</version>
<relativePath/>
</parent>
<groupId>mil.ndms.taabatch.af</groupId>
<artifactId>taaBatch</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>taaBatch</name>
<description>TAA Batch Application</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
</plugins>
</build>
</project>
My method did not throw and exception. It was handled internally so Spring see it.
Thanks to -kriegaex

Error creating bean with name 'activityController'

I'm having this problem while running on Server (Tomcat) my project. I have created a Maven project using Spring. The Java version is Java 1.8.
NO SPRING-BOOT!
Error creating bean with name 'activityController': Unsatisfied dependency expressed through field 'activityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activityService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.calendar.repository.ActivityDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Could you please help me? Thank you!
This is the code.
Thank you!!!
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.1.4.RELEASE</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Activity.java
package com.calendar.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
/**
* The persistent class for the activity database table.
*
*/
#Entity
#NamedQuery(name = "Activity.findAll", query = "SELECT a FROM Activity a")
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
#Column(name = "create_time")
private Timestamp createTime;
#Column(name = "created_by")
private String createdBy;
private String description;
#Column(name = "update_time")
private Timestamp updateTime;
#Column(name = "updated_by")
private String updatedBy;
//bi-directional many-to-one association to CalendarHeader
#OneToMany(mappedBy = "activity")
private List<CalendarHeader> calendarHeaders;
public Activity() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public List<CalendarHeader> getCalendarHeaders() {
return this.calendarHeaders;
}
public void setCalendarHeaders(List<CalendarHeader> calendarHeaders) {
this.calendarHeaders = calendarHeaders;
}
public CalendarHeader addCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().add(calendarHeader);
calendarHeader.setActivity(this);
return calendarHeader;
}
public CalendarHeader removeCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().remove(calendarHeader);
calendarHeader.setActivity(null);
return calendarHeader;
}
}
ActivityDAO.java
package com.calendar.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.calendar.entity.Activity;
#Repository
public interface ActivityDAO extends JpaRepository<Activity, Integer> {}
**ActivityDTO.java**
package com.calendar.dto;
import java.sql.Timestamp;
public class ActivityDTO {
private Integer id;
private String description;
private Timestamp createTime;
private String createdBy;
private Timestamp updateTime;
private String updatedBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
ActivityService.java
package com.calendar.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.calendar.dto.ActivityDTO;
import com.calendar.repository.ActivityDAO;
import com.calendar.entity.Activity;
#Service
public class ActivityService {
#Autowired
ActivityDAO dao;
public List<ActivityDTO> findAll() {
List<ActivityDTO> DTOList = new ArrayList<ActivityDTO>();
List<Activity> entity = dao.findAll();
if (entity != null) {
for (Activity e : entity) {
DTOList.add(getDTOFromEntity(e));
}
}
return DTOList;
};
protected ActivityDTO getDTOFromEntity(Activity entity) {
ActivityDTO activityDTO = new ActivityDTO();
activityDTO.setId(entity.getId());
activityDTO.setDescription(entity.getDescription());
activityDTO.setCreatedBy(entity.getCreatedBy());
activityDTO.setCreateTime(entity.getCreateTime());
activityDTO.setUpdatedBy(entity.getUpdatedBy());
activityDTO.setUpdateTime(entity.getUpdateTime());
return activityDTO;
}
}
ActivityController.java
package com.calendar.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.calendar.dto.ActivityDTO;
import com.calendar.service.ActivityService;
#RestController
#RequestMapping("activity")
public class ActivityController {
#Autowired
private ActivityService activityService;
private ActivityService getService() {
System.out.println("service= " + activityService);
return activityService;
}
#Transactional(readOnly = true)
#GetMapping("")
#ResponseBody
public List<ActivityDTO> findAll() {
System.out.println("SIL findAll");
return getService().findAll();
}
}
AppConfig.java
package com.calendar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
Regards,
Francesco
Try adding #EnableJpaRepositories to your AppConfig:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.calendar.repository")
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
You also need to change your pom.xml. There are too many dependencies (most of them are already part of spring-data-jpa) and spring-data-jpa requires Spring 5.3.5.
<?xml version="1.0" encoding="UTF-8"?>
<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>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.3.5</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is why you should consider using Spring Boot. You will avoid issues with dependencies that do not work together.

AspectJ (Spring) + how to add the embedding of an aspect in a private method and get the specified data

I have created an aspect that should embed logging on methods marked with an annotation and with the private modifier.
In addition, I would like to add information to the log that will be available at the time of execution of the method (for example, the object with which the method works and the name of the method and the class with which it is currently working).
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.9</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
UserController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping
public List<User> getUsers() {
List<User> userList = getUsersInternal();
return userList;
}
#AuditAnnotation()
private List<User> getUsersInternal() {
List<User> allUsers = userService.getAllUsers();
return allUsers;
}
}
annotation
#Retention(RUNTIME)
#Target(METHOD)
#Documented
public #interface AuditAnnotation {
public String nameMethod() default "";
}
loggingService
public interface LoggingService {
void log(String message);
}
/**
* A dummy implementation of logging service,
* just to inject it in {#link com.aspectj.in.spring.boot.aop.aspect.auditlog.interceptor.LoggingInterceptorAspect}
* that's managed by AspectJ
*/
#Service
public class DefaultLoggingService implements LoggingService {
private static final Logger logger = LoggerFactory.getLogger("sample-spring-aspectj");
#Override
public void log(String message) {
logger.info(message);
}
}
aspect
#Aspect
#Component
public class LoggingInterceptorAspect {
#Autowired
private LoggingService loggingService;
#Pointcut("execution(private * *(..))")
public void privateMethod() {}
#Pointcut("#annotation(com.aspectj.in.spring.boot.aop.aspect.auditlog.annotation.AuditAnnotation)")
public void annotatedMethodCustom() {}
#Before("annotatedMethodCustom() && privateMethod()")
public void addCommandDetailsToMessage() throws Throwable {
ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
String message = String.format("User controller getUsers method called at %s", dateTime);
System.out.println("+++++++++++++++++++++++++");
loggingService.log(message);
}
}
configuratinAspect
#Configuration
public class LoggingInterceptorConfig {
#Bean
public LoggingInterceptorAspect getAutowireCapableLoggingInterceptor() {
return Aspects.aspectOf(LoggingInterceptorAspect.class);
}
}
test
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AspectjInSpringBootApplicationTests {
#Autowired
protected TestRestTemplate testRestTemplate;
}
class UserControllerTest extends AspectjInSpringBootApplicationTests {
#Test
void getUsers() {
String url = "/v1/users";
ParameterizedTypeReference<List<User>> typeReference =
new ParameterizedTypeReference<>() {
};
ResponseEntity<List<User>> responseEntity =
testRestTemplate.exchange(url, HttpMethod.GET, null, typeReference);
HttpStatus statusCode = responseEntity.getStatusCode();
assertThat(statusCode, is(HttpStatus.OK));
List<User> employeeDtoList = responseEntity.getBody();
System.out.println(employeeDtoList);
}
}
But at the moment I have no errors .
so far, I see that the aspect is embedded,
but I want it to be detailed so that the aspect is universal and I would not have to explicitly specify in the message in which class it works.
Maybe someone has ideas on how to fix it.
I suggest you to explore the AspectJ documentation and the JoinPoint API, too. Here is a little example in stand-alone AspectJ without Spring. You can adjust it to your needs:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
Application application = new Application();
System.out.println(application.add(4, application.multiply(2, 3)));
application.divide(5, 0);
}
private int add(int i, int j) {
return i + j;
}
private int multiply(int i, int j) {
return i * j;
}
private double divide(int i, int j) {
return i / j;
}
}
package de.scrum_master.aspect;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class MyAspect {
#Before("execution(private * *(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println(joinPoint);
System.out.println(" Signature: " + joinPoint.getSignature());
System.out.println(" Target: " + joinPoint.getTarget());
System.out.println(" Arguments: " + Arrays.deepToString(joinPoint.getArgs()));
}
#AfterReturning(pointcut = "execution(private * *(..))", returning = "result")
public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
System.out.println(" Result: " + result);
}
#AfterThrowing(pointcut = "execution(private * *(..))", throwing = "exception")
public void afterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
System.out.println(" Exception: " + exception);
}
}
Console log:
Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
execution(int de.scrum_master.app.Application.multiply(int, int))
Signature: int de.scrum_master.app.Application.multiply(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [2, 3]
Result: 6
execution(int de.scrum_master.app.Application.add(int, int))
Signature: int de.scrum_master.app.Application.add(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [4, 6]
Result: 10
10
execution(double de.scrum_master.app.Application.divide(int, int))
Signature: double de.scrum_master.app.Application.divide(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [5, 0]
Exception: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
at de.scrum_master.app.Application.divide(Application.java:19)
at de.scrum_master.app.Application.main(Application.java:7)
In addition to the context data I printed here, you can also get annotations and their properties, method parameter names (even though I think that is unnecessary and availability depends on compilation options) etc.

JavaFX 12 maven and Spring

I'm trying to add spring to my pom
but I'm wondering if my build will look like this.
Could someone help me how can I do this spring integration with java fx?
my pom:
<properties>
<java.version>12</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12.0.2</version>
</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-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<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.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>
</plugin>
</plugins>
</build>
</project>
main class:
public class App extends Application {
private static Scene scene;
#Override
public void start(Stage stage) throws IOException {
scene = new Scene(loadFXML("primary"));
stage.setScene(scene);
stage.show();
}
static void setRoot(String fxml) throws IOException {
scene.setRoot(loadFXML(fxml));
}
private static Parent loadFXML(String fxml) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
return fxmlLoader.load();
}
public static void main(String[] args) {
launch();
} }
I searched and found nothing about integrating javafx with spring
Could someone help me how I can integrate spring?
I tried to use what I used in my swing project but it didn't work out
Your main app has to maintain Spring's application context like this.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
#Configuration // or #SpringBootApplication if you used spring boot.
public class App extends Application {
private static Scene scene;
private AbstractApplicationContext context;
#Override
public void init() throws Exception {
this.context = new AnnotationConfigApplicationContext(App.class);
super.init();
}
#Override
public void start(Stage stage) throws IOException {
SpringFxmlLoader loader = new SpringFxmlLoader(this.context);
Parent root = loader.loadFromResource("primary.fxml");
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
use SpringFxmlLoader for returning a controller as a spring bean.
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.springframework.context.ApplicationContext;
import javafx.fxml.FXMLLoader;
public class SpringFxmlLoader extends FXMLLoader {
private ApplicationContext context;
protected SpringFxmlLoader() {
}
public SpringFxmlLoader(ApplicationContext context) {
this.context = context;
setControllerFactory(context::getBean); // return a spring bean from spring's application context.
}
public ApplicationContext getContext() {
return this.context;
}
public <T> T loadFromResource(String resource) throws IOException {
return loadFromResource(resource, null);
}
public <T> T loadFromResource(String resource, Class<?> root) throws IOException {
URL resourceURL = context.getResource(resource).getURL();
setLocation(resourceURL);
if(root != null) setRoot(root);
try (InputStream fxml = resourceURL.openStream()) {
return load(fxml);
}
}
}
Your controller should be looked like this as a spring bean.
#Controller
#Scope("prototype")
public class PrimaryController {
#FXML private Parent rootView;
#FXML private TitledPane settingPane;
#Autowired private SomeBean someBean; // now you can autowire spring beans.
// braa....
}
Don't forget specify the controller class in your primary.fxml with fx:controller attribute.

Spring Boot 5 multiple JUnit JPA test files wiring

I have two tests files in project.
One is testing directly my persistence layer :
#RunWith(SpringRunner.class)
#DataJpaTest
public class UserTests {
#Autowired
private TestEntityManager entityManager;
#Autowired
private UserRepository repository;
#Test
public void whenFindByEmail_thenReturnUser() {
// given
User user = new User("email#email.com", "12345678", "Some Name");
entityManager.persist(user);
entityManager.flush();
// when
User found = repository.findByEmail(user.getEmail());
// then
assertThat(found.getName()).isEqualTo(user.getName());
assertThat(found.getEmail()).isEqualTo(user.getEmail());
assertThat(found.getPasswordHash()).isEqualTo(user.getPasswordHash());
}
}
The other one is testing a service using the persistence layer :
#RunWith(SpringRunner.class)
#DataJpaTest
public class UserServiceTests {
#Autowired
private UserService service;
#Test
public void testSuccessfullUserCreation() {
UserCreationResult res = service.createUser("anything#anything.com", "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testWrongEmailUserCreation() {
UserCreationResult res = service.createUser("anything#anything", "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.INVALID_EMAIL);
}
#Test
public void testTooShortPasswordUserCreation() {
String shortPassword =
String.join("", Collections.nCopies(UserService.minPasswordLength - 1, "0"));
UserCreationResult res = service.createUser("anything#anything.com", shortPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.WRONG_PASSWORD_LENGTH);
}
#Test
public void testTooLongPasswordUserCreation() {
String longPassword =
String.join("", Collections.nCopies(UserService.maxPasswordLength + 1, "0"));
UserCreationResult res = service.createUser("anything#anything.com", longPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.WRONG_PASSWORD_LENGTH);
}
#Test
public void testMaxLengthPasswordUserCreation() {
String maxPassword =
String.join("", Collections.nCopies(UserService.maxPasswordLength, "0"));
UserCreationResult res = service.createUser("anything#anything.com", maxPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testMinLengthPasswordUserCreation() {
String minPassword =
String.join("", Collections.nCopies(UserService.minPasswordLength, "0"));
UserCreationResult res = service.createUser("anything#anything.com", minPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testReservedEmailUserCreation() {
String email = "email#email.com";
UserCreationResult res = service.createUser(email, "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
res = service.createUser(email, "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.RESERVED_EMAIL);
}
}
First, my service autowiring wasn't working (UnsatisfiedDependencyException) so I had to add :
#ComponentScan("my.service.package") annotation to the test class.
This made the tests of UserServiceTests work when they were run independently (using eclipse to run only this class).
But when running all the tests of my app (in eclipse or with a good old mvn clean test), I had the same error on the same test class.
I tried adding the same component scan annotation to the other test class (UserTests) then everything worked.
I removed the component scan annotation from UserServiceTests and it still works.
I obviously deduced that the order the tests are executed matters.
Here are my 3 questions, the real one being the last one :
In the first place why do I have to put this component scan annotation even if my class is properly annotated #Service (so should be detected as a bean) ?
How is it that the order of tests matters ?
How can I have multiple JPA tests files that would run with a proper dependency injection independently ?
Here is my service class :
#Service
public class UserService {
#Autowired
private UserRepository repository;
public static final int minPasswordLength = 8;
public static final int maxPasswordLength = 50;
public static enum UserCreationResult {
OK, INVALID_EMAIL, RESERVED_EMAIL, WRONG_PASSWORD_LENGTH, UNKNOWN_ERROR
}
#Transactional
public UserCreationResult createUser(String email, String password, String name) {
if (password.length() < minPasswordLength || password.length() > maxPasswordLength) {
return UserCreationResult.WRONG_PASSWORD_LENGTH;
}
if (!EmailValidator.getInstance().isValid(email)) {
return UserCreationResult.INVALID_EMAIL;
}
final User existingUser = repository.findByEmail(email);
if (existingUser != null) {
return UserCreationResult.RESERVED_EMAIL;
}
final User user = repository.save(new User(email, password, name));
return user == null ? UserCreationResult.UNKNOWN_ERROR : UserCreationResult.OK;
}
}
And there is my pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<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>com.somedomain</groupId>
<artifactId>ws-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>My App</name>
<description>My app's description</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Thanks to this question and answer I was able to make my tests work with proper configuration.
In my UserServiceTests, the service was basically not autowired because that's the expected behavior of #DataJpaTest : it doesn't scan for regular beans.
So I used #SpringBootTest for this class and removed the component scanning in both test classes.
After that, some of my service tests were failing because with #SpringBootTest, the database is not reset after each test.
I added a simple repository cleaning after each service test and everything works fine.
This question still remains :
How is it that the order of tests matters ?
Here are my new test classes :
Service tests :
#RunWith(SpringRunner.class)
#SpringBootTest
public class UserServiceTests {
#Autowired
private UserService service;
#Autowired
private UserRepository repository;
#After
public void cleanUsers() {
repository.deleteAll();
}
#Test
public void testSuccessfullUserCreation() {
UserCreationResult res = service.createUser("anything#anything.com", "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testWrongEmailUserCreation() {
UserCreationResult res = service.createUser("anything#anything", "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.INVALID_EMAIL);
}
#Test
public void testTooShortPasswordUserCreation() {
String shortPassword =
String.join("", Collections.nCopies(UserService.minPasswordLength - 1, "0"));
UserCreationResult res = service.createUser("anything#anything.com", shortPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.WRONG_PASSWORD_LENGTH);
}
#Test
public void testTooLongPasswordUserCreation() {
String longPassword =
String.join("", Collections.nCopies(UserService.maxPasswordLength + 1, "0"));
UserCreationResult res = service.createUser("anything#anything.com", longPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.WRONG_PASSWORD_LENGTH);
}
#Test
public void testMaxLengthPasswordUserCreation() {
String maxPassword =
String.join("", Collections.nCopies(UserService.maxPasswordLength, "0"));
UserCreationResult res = service.createUser("anything#anything.com", maxPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testMinLengthPasswordUserCreation() {
String minPassword =
String.join("", Collections.nCopies(UserService.minPasswordLength, "0"));
UserCreationResult res = service.createUser("anything#anything.com", minPassword, "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
}
#Test
public void testReservedEmailUserCreation() {
String email = "email#email.com";
UserCreationResult res = service.createUser(email, "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.OK);
res = service.createUser(email, "1234567890", "Test");
assertThat(res).isEqualTo(UserCreationResult.RESERVED_EMAIL);
}
}
JPA tests :
#RunWith(SpringRunner.class)
#DataJpaTest
public class UserTests {
#Autowired
private TestEntityManager entityManager;
#Autowired
private UserRepository repository;
#Test
public void whenFindByEmail_thenReturnUser() {
// given
User user = new User("user#user.com", "12345678", "Some Name");
entityManager.persist(user);
entityManager.flush();
// when
User found = repository.findByEmail(user.getEmail());
// then
assertThat(found.getName()).isEqualTo(user.getName());
assertThat(found.getEmail()).isEqualTo(user.getEmail());
assertThat(found.getPasswordHash()).isEqualTo(user.getPasswordHash());
}
}

Resources