UnsatisfiedDependencyException for #DataNeo4jTest - spring-boot

I try to test my code with Spring-Boot Neo4j but I've got an error like org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.sha.neo4j.service.UserServiceTest': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sha.neo4j.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Dependencies;
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-neo4j'
implementation 'org.springframework.boot:spring-boot-starter-web'
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'
}
testImplementation 'org.neo4j.test:neo4j-harness:4.0.0'
testImplementation 'org.neo4j:neo4j-ogm-embedded-driver:3.2.8'
}
And test class;
#RunWith(SpringRunner.class)
#DataNeo4jTest
public class UserServiceTest
{
#Autowired
private UserService userService;
#Test
public void testIt()
{
User user = new User();
user.setLastName("Test");
user.setName("Test");
userService.saveUser(user);
List<User> users = userService.findAll();
assertThat(users).hasSize(1);
}
}
In here, I've jus try to test above code with embedded driver but I've got an error like above. I don't have a specific properties (test application.properties) for test. Test works with neo4j-desktop bolt driver.
Is there any suggestion?

You should use #SpringBootTest over your tests. #DataNeo4jTest doesn't load any required services.

Related

beans.factory.UnsatisfiedDependencyException: Error creating bean with name

Errors for repository and service:
Error creating bean with name 'rimeService' defined in file [...]: Unsatisfied dependency expressed through constructor parameter 0;
nested exception is java.lang.NoClassDefFoundError: kotlin/reflect/full/KClasses
Error creating bean with name 'rimeRepository': Invocation of init method failed;
nested exception is java.lang.NoClassDefFoundError: kotlin/reflect/full/KClasses
RimeService:
#Service
class RimeService(private val repository: RimeRepository) {
fun findRimes(character: String) = repository.findByCharactersContains(character)
}
RimeRepository:
#Repository
interface RimeRepository: JpaRepository<Rime, Int> {
fun findByCharactersContains(character: String): List<Rime>
}
Controller:
#Controller
#RequestMapping("/rimes")
class RimeController(private val service: RimeService) {
#GetMapping("/{character}")
fun getByCharacter(#PathVariable character: String) = service.findRimes(character)
}
dependencies:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.security:spring-security-test'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}
In addition, the class and methods in controller is grayed out in Intelij, which means those are never used.
Please let me know if there's anything wrong with my configuration.
Thank you.

Quarkus - Unsatisfied dependency for type org.eclipse.microprofile.jwt

I was trying to implement the JWT token for one my Quarkus application but somehow getting an exception - Unsatisfied dependency for type org.eclipse.microprofile.jwt.JsonWebToken and qualifiers [#Default]
My Quarkus application is fairly simple and having one rest endpoint -
#Path("/jwt")
#RequestScoped
public class JWTRestController {
#Inject
JsonWebToken jwt;
#GET()
#Path("permit-all")
#PermitAll
#Produces(MediaType.TEXT_PLAIN)
public String hello(#Context SecurityContext ctx) {
Principal caller = ctx.getUserPrincipal();
String name = caller == null ? "anonymous" : caller.getName();
String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme());
return helloReply;
}
}
But when i try to run my quarkus application -
gradlew quarkusDev
Log stacktrace
> Task :quarkusDev
Port 5005 in use, not starting in debug mode
2020-04-05 15:57:49,789 INFO [org.jbo.threads] (main) JBoss Threads version 3.0.1.Final
2020-04-05 15:57:50,158 ERROR [io.qua.dev.DevModeMain] (main) Failed to start Quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type org.eclipse.microprofile.jwt.JsonWebToken and qual
ifiers [#Default]
- java member: com.jhooq.JWTRestController#jwt
- declared on CLASS bean [types=[com.jhooq.JWTRestController, java.lang.Object], qualifiers=[#Default, #Any], target=com.jhooq.JWTRestController]
at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:910)
at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:232)
at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:130)
at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:291)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
Am i really missing something here?
Here is my build.gradle
plugins {
id 'java'
id 'io.quarkus'
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
implementation 'io.quarkus:quarkus-resteasy'
testImplementation 'io.quarkus:quarkus-junit5'
testImplementation 'io.rest-assured:rest-assured'
testImplementation 'io.quarkus:quarkus-smallrye-jwt'
testImplementation 'io.quarkus:quarkus-resteasy-jsonb'
implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1'
}
group 'com.jhooq'
version '1.0.0-SNAPSHOT'
compileJava {
options.compilerArgs << '-parameters'
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
The problem lies here:
testImplementation 'io.quarkus:quarkus-smallrye-jwt'
testImplementation 'io.quarkus:quarkus-resteasy-jsonb'
implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1'
The quarkus-smallrye-jwt and quarkus-resteasy-jsonb dependencies are part of the application, not part of tests. These must be implementation, not testImplementation.
At the same time, you can remove implementation 'org.eclipse.microprofile.jwt:microprofile-jwt-auth-api:1.1.1', this it's brought in transitively by quarkus-smallrye-jwt.

Spring #Service defined in Kotlin file results in 'UnsatisfiedDependencyException: Error creating bean' when referenced

I have an existing Springboot/Java application and I wanted to start migrating the application to Kotlin. I create a #Service in Kotlin, and my unit test fails at runtime because Spring can't find my service.
My unit test:
#ExtendWith(SpringExtension::class)
#SpringBootTest(classes = arrayOf(Application::class))
class Junit5SpringKotlinTests {
#Autowired // Springboot ConfigurationProperties (application.yaml) mapped to Java bean. This works.
lateinit var applicationConfigurationJavaBean: EnvironmentProperties
fun appProperties(): EnvironmentProperties.Environment? {
return applicationConfigurationJavaBean.environments[applicationConfigurationJavaBean.activeEnvironment]
}
#Autowired
lateinit var testServiceKotlinBean :TestService // My Kotlin #Service which can not be found at runtime.
#Test
fun `ApplicationConfiguration`() {
println(appProperties()?.baseClientId)
testServiceKotlinBean.hello()
}
}
My Kotlin service: TestService.kt
import org.springframework.stereotype.Service
#Service
class TestService {
fun hello() {
println("hello from service")
}
}
My error at runtime executing the unit test:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'Junit5SpringKotlinTests': Unsatisfied dependency expressed through field 'testServiceKotlinBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'api.model.TestService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'api.model.TestService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
FWW, I am able to write JUnit5 SpringBootTests in Kotlin test code and exercise all my Java components, so this has something to do with Kotlin components being discovered at runtime by Spring. Java components work.
I suspected this might be a build problem and have seen similar issues. I have the following included in my pom.xml:
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
so that wasn't the problem.
The problem was the package name I used for the Kotlin service. Kotlin is nice in that I don't have put my files in the same package path like java. But my Spring classpath scanning was relying on a package: A.B.C and below and my Kotlin path only had C. I changed the package name in my Kotlin file to be A.B.C.TestService and all is fine. Yay.

SpringBoot EntityManagerFactory not found

So, trying to run first sprinboot application with JPA implementation and got the following error :
Description:
Field personneDAO in com.example.demo.controller.PersonneController required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
tried to add #Repositoy on my repo, and #EnableJpaRepositories to the main, but it doesn't helps...
the repository (nothing too fancy):
#Repository
public interface PersonneDAO extends JpaRepository<Personne, Integer>{
}
the main :
#SpringBootApplication
#EnableJpaRepositories(basePackages ="com.example.demo.repository")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
gradle dependencies :
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.16.Final'
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.0.6.RELEASE'
testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.5.1.jre9-preview'
}
Any ideas guys? :/
PS : forgot the application.properties
spring.mvc.view.prefix = /WEB-INF/
spring.mvc.view.suffix = .jsp
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:sqlserver://localhost/DB_TEST
spring.datasource.username=sa
spring.datasource.password=Pa$$w0rd
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
JPA will not get auto-configured without spring-boot-starter-data-jpa as a dependency. With the dependency in place, you shouldn't even need #EnableJpaRepositories.
Also, you may remove spring-data-jpa as spring-boot-starter-data-jpa already depends on that.

Spring Boot tests fail for missing javax.servlet.http.HttpServletRequest

I have a springboot 1.5.9 using Spock for my integration tests. These tests all worked before with SpringBoot 1.3.5 but after upgrading Spring and Spock, I get the following when I run
gradle clean build test
Error on each integration test:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.http.HttpServletRequest' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
My dependencies:
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
dependencies {
querydslapt group: 'com.mysema.querydsl', name: 'querydsl-jpa', version: '2.8.0', classifier: 'apt-one-jar', transitive: false
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion")
compile("org.springframework.security:spring-security-web:4.0.0.M1")
compile("org.springframework.security:spring-security-config:4.0.0.M1")
compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE')
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.5.0')
compile("org.hibernate:hibernate-core:4.3.4.Final")
compile("org.hibernate:hibernate-entitymanager:4.3.4.Final")
compile("org.hibernate:hibernate-validator")
compile("org.apache.velocity:velocity:1.7")
compile('javax.mail:mail:1.4.1')
compile("org.springframework:spring-context-support")
compile("mysql:mysql-connector-java:5.1.6")
compile("com.h2database:h2:1.3.172")
compile("joda-time:joda-time:2.3")
compile("org.codehaus.groovy.modules.http-builder:http-builder:0.7.1")
compile('org.jadira.usertype:usertype.jodatime:2.0.1')
compile("org.liquibase:liquibase-core")
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
testCompile(group: 'org.spockframework', name: 'spock-core', version: '1.1-groovy-2.4') {
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
}
testCompile(group: 'org.spockframework', name: 'spock-spring', version: '1.1-groovy-2.4') {
exclude group: 'org.spockframework', module: 'spock-core'
exclude group: 'org.spockframework', module: 'spring-beans'
exclude group: 'org.spockframework', module: 'spring-test'
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
}
testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion")
testCompile('org.codehaus.groovy.modules.http-builder:http-builder:0.7+')
testCompile("junit:junit")
}
And all my spock tests use this as their base:
#ContextConfiguration(classes = MainClass)
#WebAppConfiguration()
#SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.NONE)
public class BaseSpecification extends Specification {
}
And here is the main class:
#ComponentScan
#EnableAutoConfiguration
#EnableGlobalMethodSecurity(securedEnabled = true)
public class MainClass {
public static void main(String[] args) {
ApplicationContext mc = SpringApplication.run( MainClass.class, args );
}
}
For Spring based test, we need the SpringJUnit4ClassRunner so application context is created.
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = MainClass.class)
#WebAppConfiguration
#SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.NONE)
public class BaseSpecification extends Specification {
}
and also add
compile("org.springframework.boot:spring-boot-starter-tomcat")

Resources