Micronaut equivalence of Spring ApplicationContextAware - spring

In Spring Boot, we have ApplicationContextAware interface, providing a way to set ApplicationContext, which is then used to inject some beans (that can only be initiated by the programme) into the class
// this is a Spring Boot programme
package com.example.demo
import org.springframework.context.ApplicationContextAware;
public class MyClass implements ApplicationContextAware {
private MyBean myBean;
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext= applicationContext;
}
public void setBean(){
this.myBean= applicationContext.getBean(MyBean.class);
}
}
I was trying to find such a method in Micronaut framework. I looked into documentation and tried a few classes like ApplicationContextConfigurer, ApplicationContextBuilder etc. but none seemed to work
By looking at what the code above does, is there a way to achieve the same thing in Micronaut?
More background:
I deployed a Micronaut application onto AWS Lambda and got NullPointerException. I referred to this post, which mentioned ApplicationContextAware. This post uses Spring, but I suspect the underlysing mechanism should be similar
Posting my pom.xml, as asked by the comments
<?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.example</groupId>
<artifactId>MicronautExp</artifactId>
<version>0.1</version>
<packaging>${packaging}</packaging>
<parent>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-parent</artifactId>
<version>3.7.4</version>
</parent>
<properties>
<packaging>jar</packaging>
<jdk.version>11</jdk.version>
<release.version>11</release.version>
<micronaut.version>3.7.4</micronaut.version>
<micronaut.runtime>netty</micronaut.runtime>
<micronaut.runtime>lambda</micronaut.runtime>
<exec.mainClass>com.example.Application</exec.mainClass>
<exec.mainClass>io.micronaut.function.aws.runtime.MicronautLambdaRuntime</exec.mainClass>
</properties>
<repositories>
<repository>
<id>central</id>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-inject</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-validation</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-jackson-databind</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.test</groupId>
<artifactId>micronaut-test-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- micronaut http dependencies. Forgot why they are here, but better not touch it-->
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-client</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-server-netty</artifactId>
<scope>compile</scope>
</dependency>
<!-- graalvm compilers. Forgot why they are here, but better not touch it-->
<dependency>
<groupId>org.graalvm.nativeimage</groupId>
<artifactId>svm</artifactId>
<version>22.2.0</version>
</dependency>
<dependency>
<groupId>org.graalvm.sdk</groupId>
<artifactId>graal-sdk</artifactId>
<version>22.2.0</version>
</dependency>
<!-- micronaut email dependency-->
<dependency>
<groupId>io.micronaut.email</groupId>
<artifactId>micronaut-email-javamail</artifactId>
</dependency>
<dependency>
<groupId>io.micronaut.email</groupId>
<artifactId>micronaut-email</artifactId>
<version>1.5.0</version>
</dependency>
<!-- AWS Lambda dependencies-->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>io.micronaut.aws</groupId>
<artifactId>micronaut-function-aws-api-proxy</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut.aws</groupId>
<artifactId>micronaut-function-aws-api-proxy-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micronaut.aws</groupId>
<artifactId>micronaut-function-aws-custom-runtime</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.micronaut.build</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<!-- Uncomment to enable incremental compilation -->
<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->
<annotationProcessorPaths combine.children="append">
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-validation</artifactId>
<version>${micronaut.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Amicronaut.processing.group=com.example</arg>
<arg>-Amicronaut.processing.module=MicronautExp</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

In Micronaut you don't need such an interface. If any Micronaut managed bean accepts the ApplicationContext as a constructor parameter, or includes a property marked with #Inject, the ApplicationContext will be injected.
Ex:
import io.micronaut.context.ApplicationContext;
import io.micronaut.http.annotation.*;
#Controller("/demo")
public class DemoController {
private final ApplicationContext applicationContext;
public DemoController(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Get(uri="/", produces="text/plain")
public String index() {
// ...
}
}

Related

ClassNotFoundException org.neo4j.graphdb.factory.GraphDatabaseFactory

I'm trying to test my API project. I'm having this issue :
Caused by: java.lang.ClassNotFoundException: org.neo4j.graphdb.factory.GraphDatabaseFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 147 more
Anyone has faced the issue ?
From the question SpringBoot - BeanDefinitionOverrideException: Invalid bean definition
I know I need to activate bean overriding so I have activated it.
#RunWith(SpringRunner.class)
#SpringBootTest(properties = "spring.main.allow-bean-definition-overriding=true")
#ContextConfiguration(classes = { TestConfiguration.class})
#ActiveProfiles(profiles = "test")
public class EmployeeRepositoryTest {
#Autowired
private EmployeeService employeeService;
#Test
public void testIt() {
Employee user = new Employee(10, "Test");
employeeService.addEmployee(user);
Iterable<Employee> allEmp = employeeService.findAll();
assertThat(allEmp).hasSize(1);
}
}
Here is my configuration class :
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = { "com.neo4j.interview.api" })
#EnableNeo4jRepositories(basePackages = "com.neo4j.interview.api.repository")
#Profile({ "embedded", "test" })
public class TestConfiguration {
#Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
org.neo4j.ogm.config.Configuration config = new Builder().build();
return config;
}
#Bean()
public SessionFactory sessionFactory() {
return new SessionFactory(getConfiguration(), "com.neo4j.interview.api.domain");
}
#Bean
public Neo4jTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
}
Here 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 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.2.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.neo4j.interview.api</groupId>
<artifactId>neo4jtestapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>neo4jtestapi</name>
<description>Neo4j test project API</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<neo4j.version>4.0.2</neo4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-bolt</artifactId>
<version>${neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-dbms</artifactId>
<version>${neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>${neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-graphdb-api</artifactId>
<version>${neo4j.version}</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-embedded-driver</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.8</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.neo4j.interview.api.Neo4jtestApiApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Update:
If I remove overriding line, employeeService is null in EmployeeRepositoryTest

How to test Spring CrudRepository using #DataJpaTest in Spring boot 2.1.0.M4 using Junit 5

I cannot test my spring crud repository using spring boot 2.1.0.M4 with Junit5 and #DataJpaTest.
I am using the following spring crud repository interface.
#Repository
public interface DestinationRepository extends CrudRepository<Destination, String> {
Optional<Destination> findCityCode(String code, String cityIsolci);
}
And this is my unit test class
package com.test.repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.test.Destination;
import java.util.Optional;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#DataJpaTest
// #ExtendWith(SpringExtension.class)
public class DestinationRepositoryTest {
#Autowired
private TestEntityManager entityManager;
#Autowired
private DestinationRepository destinationRepository;
#Test
public void whenfindByCodeAndCityIsolciThenReturnDestination() throws Exception {
this.entityManager.persist(new Destination("DXB", "Y", "Dubai gate comment"));
Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");
Assert.assertTrue(found.isPresent());
// assertThat(user.getVin()).isEqualTo("1234");
}
// #Test
// public void whenfindByCodeAndCityIsolciThenReturnDestination() {
// // given
// Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
//
// // when
// Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");
//
// // then
// Assert.assertTrue(found.isPresent());
// Assert.assertEquals(found.get().getGateComment(), dubai.getGateComment());
// }
// #Test
// public void shouldFindAllDestinations() {
// Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
// Destination syd = destinationRepository.save(new Destination("SYD", "Y", "SYD gate comment"));
//
// Iterable<Destination> destinations = destinationRepository.findAll();
//
// assertThat(destinations).hasSize(2).contains(dubai, syd);
// }
}
This 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>
<parent>
<groupId>***.***.***</groupId>
<artifactId>******</artifactId>
<version>1.0.0</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<artifactId>*****</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>TEST</description>
<prerequisites>
<maven>${maven.version}</maven>
</prerequisites>
<properties>
<start-class>c*.*.Application</start-class>
<junit.jupiter.version>5.2.0</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-rsa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Sql server driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<!-- Lombok dependencies -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- Commons dependencies -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
</dependency>
<!-- Logging dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
</dependency>
<!-- Swagger dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring REST Docs dependencies -->
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-webtestclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Auto REST Docs dependencies -->
<dependency>
<groupId>capital.scalable</groupId>
<artifactId>spring-auto-restdocs-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<!-- JUnit Jupiter API and Engine -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-test -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.1.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>5.4.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.yml</include>
</includes>
<excludes>
<exclude>**/*.jks</exclude>
</excludes>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.jks</include>
</includes>
<excludes>
<exclude>**/*.xml</exclude>
<exclude>**/*.properties</exclude>
<exclude>**/*.yml</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>com.github.ekryd.sortpom</groupId>
<artifactId>sortpom-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<excludeFromFailureFile>${project.basedir}/exclude-pmd.properties</excludeFromFailureFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
</plugin>
<plugin>
<groupId>org.gaul</groupId>
<artifactId>modernizer-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>qa</id>
<properties>
<spring.profiles.active>qa</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
<profile>
<id>eclipse</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
I just want to know what is the right set of annotations to run the test successfully.
I have tried using different combinations of
#DataJpaTest
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class)
#ExtendWith(SpringExtension.class)
If I just use #DataJpaTest with #RunWith(SpringRunner.class)
I get the following error:
[ERROR] whenfindByCodeAndCityIsolciThenReturnDestination Time elapsed: 1.237 s <<< ERROR!
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: EK_DESTINATIONS in statement [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: EK_DESTINATIONS
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
P.S. Just want to mention that this was working fine with spring boot version 2.0.3.RELEASE.
I can see from the release notes (https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1.0-M2-Release-Notes) that a bootstrap mode was introduced. This may or may not be causing the problem.
Do not mix #SpringBootTest with #DataJpaTest
From JavaDoc's one can read:
Annotation that can be used in combination with {#code
#RunWith(SpringRunner.class)} for a typical JPA test. Can be used
when a test focuses only on JPA components.
For full integration tests you should instead use #SpringBootTest
If you are looking to load your full application configuration, but use an embedded database, you should consider {#link SpringBootTest
#SpringBootTest} combined with {#link AutoConfigureTestDatabase
#AutoConfigureTestDatabase} rather than this annotation.
I think your problem is cause by changed naming strategy. Try to check this issue

#DataMongoTest is creating a null MongoTemplate

I have been trying to follow the instructions in the link below to try to add an automatically configured Embedded MongoDB Instance for Cucumber Integration testing. This is currently not working, since the I keep getting a null MongoTemplate. I thought that #DataMongoTest would automatically configure "#Autowired private MongoTemplate mongoTemplate;" Is this not the case? Below is my code:
mongoTemplate.save(doc, collection); throws a nullpointer exception.
#SpringBootTest(classes = AppCommentApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#DataMongoTest
public abstract class SpringIntegrationTest {
#Value("${local.server.port}")
public int port;
#Autowired
private MongoTemplate mongoTemplate;
protected void importJSON(String collection, String file) {
try {
for (String line : FileUtils.readLines(new File(file), "utf8")) {
Document doc = Document.parse(line);
mongoTemplate.save(doc, collection);
}
} catch (IOException e) {
throw new RuntimeException("Could not import file: " + file, e);
}
}
}
#RunWith(Cucumber.class)
#CucumberOptions(format = "pretty",
features = "src/test/resources/features",
glue = "com.app.comment.cucumber")
public class CucumberIntegrationTest {
}
public class StepDefinitions extends SpringIntegrationTest {
private Map<String, String> headerMap = null;
private String postBody = null;
private String putBody = null;
private String formData = null;
private Response response = null;
private String data = null;
private final static String MONGODB_COLLECTION = "comment";
private final static String MONGODB_DATA = "src/test/resources/mongodb-data/data.txt";
#Before
public void setup() {
importJSON(MONGODB_COLLECTION, MONGODB_DATA);
}
#Given("^the header information$")
public void the_header_information(Map<String, String> headerMap) throws Throwable {
this.headerMap = headerMap;
}
#Given("^post message body \"(.*?)\"$")
public void post_message_body(String postBody) throws Throwable {
this.postBody = postBody;
}
#Given("^put message body \"(.*?)\"$")
public void put_message_body(String putBody) throws Throwable {
this.putBody = putBody;
}
}
pom.xml 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.app.comment</groupId>
<artifactId>app-comment-api</artifactId>
<version>1.0.4</version>
<packaging>jar</packaging>
<name>app-comment-api</name>
<description>App Comments Microservice</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.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>
<log4j.version>2.4.1</log4j.version>
<commons.lang3.version>3.3.2</commons.lang3.version>
<guava.version>19.0</guava.version>
<swagger.version>2.4.0</swagger.version>
<surefire.junit47.version>2.18.1</surefire.junit47.version>
<rest-assured.version>2.8.0</rest-assured.version>
<jacoco.version>0.7.5.201505241946</jacoco.version>
<powermock.version>1.6.4</powermock.version>
<commons.io.version>2.4</commons.io.version>
<httpclient.version>4.5.1</httpclient.version>
<jayway.jsonpath.version>2.2.0</jayway.jsonpath.version>
<jjwt.version>0.6.0</jjwt.version>
<docker.image.prefix>app</docker.image.prefix>
<docker.spotify.plugin.version>0.4.5</docker.spotify.plugin.version>
<jacoco.maven.plugin.version>0.7.7.201606060606</jacoco.maven.plugin.version>
<fongo.version>2.0.11</fongo.version>
<cucumber.version>1.2.5</cucumber.version>
<gatling.highcharts.version>2.2.3</gatling.highcharts.version>
<gatling.plugin.version>2.2.1</gatling.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-docs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- Utility -->
<dependency>
<groupId>com.logentries</groupId>
<artifactId>logentries-appender</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${jayway.jsonpath.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.5</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<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-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.highcharts.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Package as a docker image -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>${docker.spotify.plugin.version}</version>
<configuration>
<serverId>docker-hub</serverId>
<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
<imageTags>
<imageTag>${project.version}</imageTag>
</imageTags>
</configuration>
</plugin>
<!-- Runs Code Coverage Reports -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.maven.plugin.version}</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>cucumber-tests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<!-- Include your Cucumber tests, as an example -->
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*Simulation.scala</exclude>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>gatling-tests</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<simulationClass>com.app.comment.gatling.MicroserviceServiceSimulation</simulationClass>
</configuration>
</execution>
</executions>
<configuration>
<configFolder>${project.basedir}/src/test/resources</configFolder>
<dataFolder>${project.basedir}/src/test/resources/data</dataFolder>
<resultsFolder>${project.basedir}/target/gatling/results</resultsFolder>
<bodiesFolder>${project.basedir}/src/test/resources/bodies</bodiesFolder>
<simulationsFolder>${project.basedir}/src/test/scala</simulationsFolder>
<runDescription>This-is-the-run-description</runDescription>
<!-- <noReports>false</noReports> -->
<!-- <reportsOnly>directoryName</reportsOnly> -->
<!-- <simulationClass>foo.Bar</simulationClass> -->
<!-- <jvmArgs> -->
<!-- <jvmArg>-DmyExtraParam=foo</jvmArg> -->
<!-- </jvmArgs> -->
<!-- <fork>true</fork> -->
<!-- <propagateSystemProperties>true</propagateSystemProperties> -->
<!-- <failOnError>true</failOnError> -->
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test
If you use JUnit 4, you should have RunWith(SpringRunner.class). With JUnit 5 is not necessary.
And, #SpringBootTest cannot coexist with #DataMongoTest, because they are for different parts of the application and the latter is only for data part, while the former is for app part. (Actually the #BootstrapWith of them will conflict if you put these two together and the test cannot be start)
#DataMongoTest will use embedded database and you don't need to do extra config other than #Autowired the mongotemplate. If you want to use real db, do this:
#DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
My test is like this and it works:
#ActiveProfiles("db")
#DataMongoTest
class CouponTypeRefRepositoryTest {
#Autowired
private CouponTypeRefRepository repository; // a simple repository extending `DataMongoRepository`
#Autowired
private MongoTemplate mongoTemplate;
#BeforeEach
void prepare() {
CouponTypeRef toSave = CouponTypeRef.builder()
.id((short)1)
.duration((short)1)
.couponType("COMMERCIAL")
.couponTypeRefConfig(CouponTypeRefConfig.REFUNDABLE_NORMAL)
.build();
mongoTemplate.save(toSave, "CouponTypeRef");
}
#Test
void shouldReturnCouponTypeRef() {
Optional<CouponTypeRef> optional = repository.findById((short)1);
assertThat(optional.isPresent(), is(true));
assertThat(optional.get().getCouponType(), is("COMMERCIAL"));
assertThat(optional.get().getDuration(), is((short)1));
assertThat(optional.get().getCouponTypeRefConfig(), is(CouponTypeRefConfig.REFUNDABLE_NORMAL));
}
My dependency is:
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive:2.2.1.RELEASE'
The db profile config:
spring:
data:
mongodb:
host: localhost
port: 27017
database: app1
More info here:
https://www.baeldung.com/spring-boot-embedded-mongodb
https://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/html/boot-features-testing.html
Adding #RunWith(SpringRunner.class) annotation to SpringIntegrationTest class should work. SpringRunner will enable Autowiring of beans into your test class.
Try putting an #DirtiesContext on your test class.

error while running integration test with spring boot and testng

We are trying to run integration test using testng and springboot.app is running fine and we are able run standalone test using eclipse.but when we run testcase using maven command line.i am getting following exception
org.apache.coyote.AbstractProtocol start
SEVERE: Failed to start end point associated with ProtocolHandler ["http-nio-8080"]
java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
if we try to load context.xml for running testcase then each testcase is trying to load its own context and testcase are failing with host not found exception.
base testcase class
//#ContextConfiguration(locations={"classpath:objectModelContext.xml"})
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseITCase extends com.test.common.BaseITCase {
protected static final String baseUrl = "http://localhost:" + port + "/test/api/";
protected String getAdminToken(String username, String password, String deviceId) throws Exception {
}
}
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>om.test</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.test.App</start-class>
<tomcat.version>7.0.65</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections-maven</artifactId>
<version>0.9.9-RC2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1200-jdbc41</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- only dependency needed -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.googlecode.plist</groupId>
<artifactId>dd-plist</artifactId>
<version>1.8</version>
<!-- corresponds to r108 -->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<type>jar</type>
<scope>test</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>post-integration-test</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
<configuration>
<maxAttempts>600</maxAttempts>
<fork>true</fork>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<!--$NO-MVN-MAN-VER$-->
<executions>
<execution>
<id>integration-tests</id>
<phase>integration-test</phase>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Update
Tests are run using mvn clean install
i am trying to look for example for same but i am not finding any solution.
looks like configuration is correct and server is runnig proplerly on port 8008.my app was not picking correct port while running test cases giving connection refused error
following changes were done in basetest case since SpringRunner is not required with testng
#ContextConfiguration(locations={"classpath:objectModelContext.xml"})
//#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseITCase extends com.test.common.BaseITCase {
protected static final String baseUrl = "http://localhost:" + port + "/test/api/";
protected String getAdminToken(String username, String password, String deviceId) throws Exception {
}
}

Cannot get some unit tests to run for a spring application

Spring newbie here. Trying to meld various online spring tutorials into a single working project. Started off with the spring mvc tutorial described in this link.
Now I'm trying to meld this online tutorial on Spring data jpa into the above project. As you may see in the attached figure, I've added all necessary project files (src, test, .xml files etc).
My issue is that when I do mvn package (which is what I've been using to build and run the tests), the new suite of tests for the second project do not get executed. I wonder why! Without giving away all the sources, I will show some of the most important configuration (.xml) files.
Picture showing new files added, existing files, and brief description of issue:
Note: Sorry, but some of the xml meta-data are being removed by stackoverflow. They are mostly header tags that import xml definitions and thus not that important.
orm.xml (added for spring-data-jpa exercise)
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
<named-query name="Person.findByName">
<query>select p from Person p where p.firstName = :firstName AND p.lastName = :lastName</query>
</named-query>
persistence.xml (added for spring-data-jpa exercise)
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="hsql">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
<property name="jadira.usertype.autoRegisterUserTypes" value="true" />
<property name="jadira.usertype.databaseZone" value="jvm" />
</properties>
</persistence-unit>
root-context.xml (initially there for spring-mvc-tutorial)
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!--
CSRF protection. Here we only include the CsrfFilter instead of all of Spring Security.
See http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf for more information on
Spring Security's CSRF protection
-->
<bean id="csrfFilter" class="org.springframework.security.web.csrf.CsrfFilter">
<constructor-arg>
<bean class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository"/>
</constructor-arg>
</bean>
<!--
Provides automatic CSRF token inclusion when using Spring MVC Form tags or Thymeleaf. See
http://localhost:8080/#forms and form.jsp for examples
-->
<bean id="requestDataValueProcessor" class="org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor"/>
4.) controllers.xml, 5.)servlet-context.xml files are just standard files that map controllers to path, define and instantiate the dispatcher-servlet, and other beans which were already in the spring-mvc-tutorial code. I believe they don't really have anything to do with the issue described in this ticket.
Here is the test file that doesn't execute, and I'd like to have running:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#TransactionConfiguration
#Transactional
public class PersonRepositoryTest {
final Logger logger = LoggerFactory.getLogger(PersonRepositoryTest.class);
private final static Integer FIRST_ID = Integer.valueOf(1);
private final static Integer SECOND_ID = Integer.valueOf(2);
private final static int EXPECTED_COUNT = 3;
private final static String FIRST_NAME = "Joe";
private final static String LAST_NAME = "Smith";
private final static int EXPECTED_ADDRESS_COUNT = 1;
private final static String ADDR = "1060 West Addison St.";
private final static String CITY = "Chicago";
private final static String STATE = "IL";
private final static String ZIP_POSTAL = "60613";
private final static String COUNTRY = "USA";
#Autowired
private PersonRepository personRepository;
#Autowired
private ProfessionalRepository professionalRepository;
#Test
public void testFindOne() {
Person person = personRepository.findOne(FIRST_ID);
testPersonOne(person);
}
...
.. //more tests
Any help is much appreciated!
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>spring-mvc-showcase</artifactId>
<name>spring-mvc-showcase</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.2.2.RELEASE</org.springframework-version>
<org.springframework.security-version>4.0.1.RELEASE</org.springframework.security-version>
<org.aspectj-version>1.8.1</org.aspectj-version>
<org.slf4j-version>1.7.12</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.30</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Jackson JSON Processor -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Rome Atom+RSS -->
<dependency>
<groupId>com.rometools</groupId>
<artifactId>rome</artifactId>
<version>1.5.0</version>
</dependency>
<!-- JSR 303 with Hibernate Validator -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<!-- Joda Time Library -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<!-- File Upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<!-- Security (used for CSRF protection only) -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.security-version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!--Additional POM for spring-data-jpa trial -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<!-- For testing against latest Spring snapshots -->
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://repo.spring.io/snapshot</url>
<releases><enabled>false</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<!-- For developing against latest Spring milestones -->
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<argLine>-Xmx512m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<!-- Have to use version 1.2 since version 1.3 does not appear to work with ITDs -->
<version>1.2</version>
<dependencies>
<!-- You must use Maven 2.0.9 or above or these are ignored (see MNG-2972) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.0.6.v20130930</version>
<configuration>
<webApp>
<contextPath>/${project.artifactId}</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
So in your pom you are having
and the class which your saying not executing ending with only test.java.
So rename PersonRepositoryTest.java to PersonRepositoryTests.java and try again.

Resources