There doesn't seem to be a specific standard way I can find online that makes #DataJpaTest to run correctly.
Is it true that #DataJpaTest is not being used nowadays and all tests are run at the service or controller level using #SpringBootTest?
#Repository
public interface MyBeanRepository extends JpaRepository<MyBean, Long> {
}
#Configuration
#EnableJpaRepositories("com.app.repository.*")
#ComponentScan(basePackages = { "com.app.repository.*" })
public class ConfigurationRepository {
}
#Entity
public class MyBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
#NotNull
#Size(min = 2)
private String name;
}
#DataJpaTest
public class MyBeanIntegrationTest {
#Autowired
MyBeanRepository myBeanRepository;
#Test
public void testMarkerMethod() {
}
#Test
public void testCount() {
Assertions.assertNotNull(myBeanRepository , "Data on demand for 'MyBean' failed to initialize correctly");
}
}
Running using the Eclipse->Run Junit shows these logs.
java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:73)
Running using gradle test shows the error that init failed.
FAILURE: Build failed with an exception.
* What went wrong:
Test failed.
Failed tests:
Test com.app.repository.MyBeanIntegrationTest#initializationError (Task: :test)
Here is the gradle script.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin")
}
}
plugins {
id 'org.springframework.boot' version '2.1.5.RELEASE'
id 'java'
id 'eclipse'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.app'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenLocal()
jcenter()
mavenCentral()
}
test {
useJUnitPlatform()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
runtimeOnly 'org.hsqldb:hsqldb'
testImplementation ('org.springframework.boot:spring-boot-starter-test') {
// exlcuding junit 4
exclude group: 'junit', module: 'junit'
}
/**
Test Dependencies Follows
**/
// junit 5 api
testCompile "org.junit.jupiter:junit-jupiter-api:5.2.0"
// For junit5 parameterised test support
testCompile "org.junit.jupiter:junit-jupiter-params:5.2.0"
// junit 5 implementation
testRuntime "org.junit.jupiter:junit-jupiter-engine:5.2.0"
// Only required to run junit5 test from IDE
testRuntime "org.junit.platform:junit-platform-launcher"
}
EDIT:
This has been solved and committed at the same repository.
https://github.com/john77eipe/spring-demo-1-test
It was a good idea to add a Github link. I can see following issues there:
1) If you can't have a main class annotated with #SpringBootApplication, you can use:
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.app.repository")
public class MySampleApplication {
}
2) Change annotations over your ConfigurationRepository class to:
#EnableJpaRepositories("com.app.repository")
#ComponentScan(basePackages = { "com.app.repository" })
public class ConfigurationRepository {
That should let us proceed to the next point:
3) Your MyBeanIntegrationTest should be annotated as:
#SpringBootTest(classes = MyAppApplication.class)
public class MyBeanIntegrationTest {
4) In application.yml you have a small issue with indentation in the last line. Convert tab so spaces and it should be fine.
5) Next thing is MyBeanRepository interface. You can't use a method named findOne there. Thing is, that in interfaces marked as JpaRepository or CrudRepository and so on, methods names need to follow certain rules. If you mark that it will be a repository containing type MyBean your method name should be changed to findById, because Spring will look for a property named id in your bean. Naming it by findOne will cause test to fail with:
No property findOne found for type MyBean!
After fixing these things, your tests pass on my env.
I hope this helps!
Related
I'm just getting started with Spring Boot + Kotlin and I was trying out the PagingAndSortingRepository interface for JPA so I wrote the following interface:
interface CustomerRepository : PagingAndSortingRepository<Customer, Long>
The model for Customer is below:
#Entity
data class Customer(
#Id #GeneratedValue var id: Long,
var name: String
)
Now I'm trying to hook it up with a CustomerService which looks like this:
#Service
class CustomerService(
private val customerRepository: CustomerRepository
) {
fun getAllCustomers(): Collection<Customer> = customerRepository.findAll().toList()
fun addCustomer(customer: Customer) = customerRepository.save(customer)
fun deleteCustomer(customer: Customer) = customerRepository.delete(customer)
fun updateCustomer(customer: Customer) = customerRepository.save(customer)
}
And the Application looks like this:
#SpringBootApplication
#Configuration
#EnableAutoConfiguration
#EnableJpaRepositories
class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
I've added the required dependencies I believe, which are shown below:
plugins {
id("org.springframework.boot") version "2.5.0-SNAPSHOT"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.4.30"
kotlin("plugin.spring") version "1.4.30"
}
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.apache.derby:derby:10.15.2.0")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
Spring Boot is not able to find a bean which sort of makes sense as I haven't defined one. However reading the documentation, it looks like one should be generated by Spring Boot here: Spring Boot Data Repositories
Application.properties is
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
The error message I get is:
Description:
Parameter 0 of constructor in com.ubiquifydigital.crm.service.CustomerService required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
I saw a few different posts regarding this and have tried adding the Configuration, AutoConfiguration and EnableJpaRepositories annotations however that has only changed the error to entityManagerFactory not found instead of the CustomerRepository not found.
When using default in-memory db you must define
spring.jpa.hibernate.ddl-auto=update
in application.properties as informed here. You are also missing #Autowired annotation. entityManagerFactory is missing because the default auo configuration is turned off, in that case application is expecting you to do all the necessary configuration which again you are not doing. So keep the default configuration on and change what you need.
This code is assumed in a single file.
If you are having multiple packages then you may need to add as mentioned in this link
Working code:
package com.example.demo
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import lombok.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Table
#SpringBootApplication
open class SpringBootDerbyAppApplication
fun main(args: Array<String>) {
runApplication<SpringBootDerbyAppApplication>(*args)
}
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "applog")
internal class AppLog {
#Id
#GeneratedValue
private val id: Long = 0
#JsonProperty
private val name: String? = null
}
#Configuration
open class ObjectMapperConfiguration {
#Bean
#Primary
open fun objectMapper() = ObjectMapper().apply {
registerModule(KotlinModule())
}
}
#RestController
#RequestMapping(path = ["/logs"])
internal class LogController #Autowired constructor(private val appLogRepository: AppLogRepository) {
#GetMapping(path = ["/"])
fun logs(): MutableIterable<AppLog> {
return appLogRepository.findAll()
}
#PostMapping(path = ["/"])
fun add(#RequestBody appLog: AppLog): AppLog {
appLogRepository.save(appLog)
return appLog
}
}
#Repository
internal interface AppLogRepository : CrudRepository<AppLog, Long>
gradle file
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.5.0-M1'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.apache.derby:derby'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
}
test {
useJUnitPlatform()
}
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
Goal: Adapting Prototype microservice example from Ch7 of Camel in Action by Claus Ibsen into a Gradle multi-module project.
I followed the Spring Guide to 'Creating a Multi Module Project' among other resources.
Project Structure:
+ main-mm-build
|--+ src
|--+ main
|--+ java // Spring Boot microservice (A) in this tree
|--+ build.gradle
|--+ settings.gradle
|--+ contact-manager // standalone-camel-spring microservice (B)
|--+ src
|--+ main
|--+ java // standalone-camel-spring microservice (B) here
|--+ build.gradle
Got as far as:
microservice A (Spring Boot Rest controller) can invoke microservice B (standalone Camel exposing rest() on jetty, without Spring DI).
But what I really want is to use Spring DI (without Spring Boot) in microservice B.
After making changes for camel-spring I get an error.
It's probably mucked up Gradle config, but I could use some help.
main-mm-build/contact-manager$ ../gradlew build
main-mm-build/contact-manager$ java -jar build/libs/contact-manager-1.0.jar
.
.
.
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: rest://get:/contact-manager?consumerComponentName=jetty&consumes=application%2Fjson&outType=...dto.ContactDto%5B%5D&produces=application%2Fjson&routeId=route2 due to: null
at ...impl.engine.AbstractCamelContext.getEndpoint(AbstractCamelContext.java:801)
Caused by: java.lang.NullPointerException
at ...camel.spring.spi.ApplicationContextBeanRepository.lookupByNameAndType(Ap..j:45)
Root project Gradle file:
plugins {
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
sourceCompatibility = '11'
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
allprojects {
group = 'el.cam'
repositories {
jcenter()
}
}
subprojects {
version = '1.0'
}
settings.gradle:
rootProject.name = 'main-mm-build'
include 'contact-manager'
Microservice B (contact-manager) build.gradle:
plugins {
id 'org.springframework.boot'
id 'io.spring.dependency-management'
id 'java'
id 'application'
}
sourceCompatibility = '11'
mainClassName = 'el.cam.contacts.ContactManagerApplication'
task fatJar(type: Jar) {
manifest {
attributes (
'Main-Class': mainClassName
)
}
baseName = 'contact-manager' + '-all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
dependencies {
implementation(platform("org.springframework.boot:spring-boot-dependencies:2.3.1.RELEASE"))
implementation( platform("org.apache.camel:camel-spring-boot-dependencies:3.0.0-RC3") )
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.apache.camel:camel-spring-boot-starter'
implementation 'org.apache.camel:camel-rest-starter'
implementation 'org.apache.camel:camel-jetty-starter'
implementation 'org.apache.camel:camel-jackson-starter'
implementation 'org.apache.camel:camel-swagger-java-starter'// '3.0.0-RC3'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
ContactManagerApplication.java ( I wonder if I'm configuring Spring Camel incorrectly here. All the examples I found were based on Spring boot autoconfiguration, so I just figured it out as I went.)
import el.cam.contacts.configuration.ContactManagerConfiguration;
import org.apache.camel.spring.Main;
public class ContactManagerApplication {
private static final Logger LOG = LoggerFactory.getLogger(ContactManagerApplication.class);
public static void main(String[] args) throws Exception {
Main main = new Main();
main.setApplicationContext(createSpringApplicationContext());
// main.addRoutesBuilder(contactManagerController); // DI using Spring Autowiring
main.run();
}
private static AbstractApplicationContext createSpringApplicationContext() {
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.register(ContactManagerConfiguration.class);
appContext.refresh();
return appContext;
}
}
Configuration class:
#Configuration
#ComponentScan(basePackages = "el.cam.contacts")
public class ContactManagerConfiguration {
#Autowired
ContactManagerController contactManagerController;
#Bean
public CamelContext camelContext() throws Exception {
SpringCamelContext camelContext = new SpringCamelContext();
camelContext.addRoutes(contactManagerController);
camelContext.setPropertiesComponent(properties());
camelContext.addComponent("rest", rest());
camelContext.addComponent("rest-api", restApi());
camelContext.addComponent("jetty", jetty());
return camelContext;
}
#Bean
public PropertiesComponent properties() throws Exception {
PropertiesComponent properties = new PropertiesComponent();
properties.setLocation("classpath:application.properties");
return properties;
}
#Bean
public RestComponent rest() {
RestComponent rest = new RestComponent();
return rest;
}
#Bean
public RestApiComponent restApi() {
RestApiComponent restApi = new RestApiComponent();
return restApi;
}
#Bean
public JettyHttpComponent jetty() {
JettyHttpComponent jettyHttpComponent = new JettyHttpComponent9();
return jettyHttpComponent;
}
Controller class:
#Component
public class ContactManagerController extends RouteBuilder {
#Autowired
ContactManagerService contactManagerService;
#Override
public void configure() throws Exception {
// before Camel-Spring, was using this to bind serviceBean in camel registry
// getContext().getRegistry().bind("contactManagerService", new ContactManagerService());
// TODO using default. camel property sources not picking up application.properties!
restConfiguration("jetty").port("{{port:8282}}").contextPath("api")
.bindingMode(RestBindingMode.json)
.dataFormatProperty("disableFeatures", "FAIL_ON_EMPTY_BEANS")
.apiContextPath("api-doc")
.enableCORS(true);
// define the rest service
rest("/contact-manager").consumes("application/json").produces("application/json")
.get().outType(ContactDto[].class)
.to("bean:contactManagerService?method=getContacts(${header.contactType})")
;
}
}
I tried to write an integration test for my kotlin spring application.
For this I am using the kotlintest framework. As I need to mock one of the beans in my application I also added mockk with the springmockk extension. After adding the springmockk extension the test no longer got executed.
I noticed this happens as soon as springmockk is added to the gradle testImplement dependencies, it does not even have to be imported in the application code itself.
buildscript {
ext.kotlin_version = '1.3.21'
ext.kotlintestVersion='3.4.2'
ext.spring_boot_version='2.1.4.RELEASE'
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBoot_version")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")
}
}
...
dependencies {
...
testImplementation("org.springframework.boot:spring-boot-starter-test:$springBoot_version") {
testImplementation("io.kotlintest:kotlintest-runner-junit5:$kotlintestVersion")
testImplementation("io.kotlintest:kotlintest-extensions-spring:$kotlintestVersion")
testImplementation("io.mockk:mockk:1.9.3")
// testImplementation("com.ninja-squad:springmockk:2.0.0")
}
On github I found an issue which sadly has been closed already without any proper way of using these two frameworks together: https://github.com/Ninja-Squad/springmockk/issues/26
Edit:
This is an example test, which is working when using mockkito but not when using springmockk.
#ExtendWith(SpringExtension::class)
#SpringBootTest
#AutoConfigureMockMvc
#WithMockUser(authorities = ["ROLE_TESTUSER"])
internal class MockTest : AnnotationSpec() {
override fun listeners() = listOf(SpringListener)
#Autowired
lateinit var mockMvc: MockMvc
#MockkBean
lateinit var securityHelper: SecurityHelper
#Test
fun integrationTest() {
whenever(securityHelper.someFunction()).thenReturn("test")
mockMvc.perform(MockMvcRequestBuilders.get("/some/endpoint")
).andExpect(MockMvcResultMatchers.status().isOk)
}
}
./gradlew test --rerun-tasks output:
> Configure project :
Property 'app.env' not found using profile dev: use -Papp.env=dev to define the environment for 'SPRING_PROFILES_ACTIVE'
> Task :compileKotlin
BUILD SUCCESSFUL in 56s
5 actionable tasks: 5 executed
Mock Bean with springMockk
To use #MockkBean you need to add springmockk and remove mockito core from the spring-boot-starter-test in your gradle file like:
testImplementation("io.mockk:mockk:1.9.3")
testImplementation("com.ninja-squad:springmockk:2.0.2")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "mockito-core")
}
Then your bean should be mocked with:
#MockkBean
lateinit var securityHelper: SecurityHelper
Mock Bean with MockK only
You can mock the bean just using mockK by modifying the #TestConfiguration and setting the profile of the mock Bean to be the same as the one used for your test:
#TestConfiguration
class ControllerTestConfig {
#Bean
#Profile("test")
fun securityHelper(): SecurityHelper {
val securityHelperMock: SecurityHelper = mockk(relaxed = true)
every { securityHelperMock.someFunction() } returns "test"
return securityHelperMock
}
}
You can force use the TestConfig by putting it in your #SpringBootTest:
#SpringBootTest(
classes = [YourApplication::class, ControllerTestConfig::class]
)
The assignment was simple: A SOAP web service implemented with spring boot, JDBC using Gradle.
After some time looking around the discovery was made that "Spring-WS" only works with a contract-first development style.
And we didn't want that, so we dig a little further and found out what we already know, we had to use Apache CXF for a Contract Last development style.
So off we went to search, code and test; but once the data access and facades were done we couldn’t figure out how to wire the Apache CXF WS with the Spring Boot service Façade.
So… how is it done?
This is more of a rhetorical question, because after looking around we could not find an example of Spring Boot & Apache CXF working seamlessly together, so for anyone who may be searching, here is a simple example.
First the dependencies used by the Gradle project
build.gradle file
buildscript {
ext {
springBootVersion = '2.0.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'com.telcel'
version = '0.0.1-RC'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
configurations {
providedRuntime
}
dependencies {
// Apache CXF
compile(group: 'org.apache.cxf', name: 'cxf-spring-boot-starter-jaxws', version: '3.1.15') {
exclude(module: 'spring-boot-starter-tomcat')
}
// JDBC support
compile('org.springframework.boot:spring-boot-starter-jdbc')
// embedded servlet container
compile group: 'org.springframework.boot', name: 'spring-boot-starter-undertow', version: '1.5.4.RELEASE'
runtime group: 'com.ibm.informix', name: 'jdbc', version: '4.10.10.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
testRuntime group: 'com.ibm.informix', name: 'jdbc', version: '4.10.10.0'
}
Then, we need some basic things for the CXF config.
application.properties file:
cxf.path=/service
server.address=0.0.0.0
We needed Spring Boot to create a CXF Endpoint, and we also needed that Endpoint to use our Spring aware Facade... this is where the wiring magic happened.
WebServiceConfig.java
package com.telcel.validaserie;
import com.telcel.validaserie.ui.ValidaSerieEndpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;
#Configuration
public class WebServiceConfig {
#Autowired
private Bus bus;
#Autowired
private ValidaSerieEndpoint validaSerieEndpoint;
#Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(bus, validaSerieEndpoint);
endpoint.publish("/");
return endpoint;
}
}
Notice the autowired ValidaSerieEndpoint that goes as a parameter into the EndpointImpl constructor, that's the trick, plain simple.
Finally just a simple web service implementation exposed as a Spring Bean (notice the Spring #Service stereotype)
ValidaSerieEndpoint.class
package com.telcel.validaserie.ui;
import com.telcel.validaserie.servicios.ValidaSeriesFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
#Service
#WebService
public class ValidaSerieEndpoint {
#Autowired
private ValidaSeriesFacade validaSeriesFacade;
#WebMethod
public String validaTelefonoIccid(#WebParam(name = "iccid") String iccid) {
return validaSeriesFacade.validaTelefonoIccid(iccid);
}
#WebMethod
public String validaTelefonoImei(#WebParam(name = "imei") String imei) {
return validaSeriesFacade.validaTelefonoImei(imei);
}
#WebMethod
public int validaFacturaIccid(#WebParam(name = "iccid") String iccid, #WebParam(name = "fuerza-venta") String fuerzaVenta) {
return validaSeriesFacade.validaFacturaIccid(iccid, fuerzaVenta);
}
#WebMethod
public int validaFacturaImei(#WebParam(name = "imei") String imei, #WebParam(name = "fuerza-venta") String fuerzaVenta) {
return validaSeriesFacade.validaFacturaImei(imei, fuerzaVenta);
}
}
And that's it quite simple after you look at it... hope this helps.
I have the following exception when trying to run integration test:
org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
I read many forum entries but not found any solution. My files are as follows:
Integration test
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebInitializer.class)
#DataJpaTest
#Sql("/db/data.sql")
public class ReportEventIntTest {
#Autowired
private TestRestTemplate restTemplate;
#Test
public void reportEvent() {
Map<String, String> eventMap = new HashMap<>();
this.restTemplate.postForEntity("/worker/event", eventMap, String.class);
}
}
Spring Boot config
#Configuration
#ComponentScan(basePackages = {"org.reaction.engine.collector.controller",
"org.reaction.engine.persistence.service",
"org.reaction.engine.persistence.converter",
"org.reaction.engine.service"})
#EnableAutoConfiguration
#ImportResource("classpath:applicationContext.xml")
#Profile("threadPool") // define the default profile: it can be overridden by -Dspring.profiles.active=...
public class WebInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebInitializer.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebInitializer.class, args);
}
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
return factory;
}
}
Gradle file
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE'
}
}
dependencies {
compile project(':common')
compile 'org.springframework:spring-context-support'
compile 'org.springframework.boot:spring-boot-starter'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-integration'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.apache.httpcomponents:httpclient:4.5.2'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
providedCompile 'javax.enterprise.concurrent:javax.enterprise.concurrent-api:1.0'
runtime 'mysql:mysql-connector-java'
// ---------------------- TESTING ----------------------
testCompile 'com.jayway.restassured:rest-assured:2.9.0'
testCompile 'org.springframework.boot:spring-boot-starter-test'
//testRuntime 'org.hsqldb:hsqldb'
testRuntime 'com.h2database:h2'
testRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}
Any idea?
I would greatly appreciate any thought!
Regards,
V.
I read many stackoverflow entries but I missed the following one:
#Profile cause Unable to start EmbeddedWebApplicationContext
The problem is that I defined the profile in my spring boot config class but I have to do that in the test class.
#ActiveProfiles("threadPool")