I have a Spring Boot REST service and some unit tests written for the data layer. I use the embedded MongoDB dependency to perform the basic CRUD tests for my Repository class:
public interface UserRepository extends MongoRepository<UserEntity, String> {
Optional<UserEntity> findByUsername(String username);
}
I load the data from a JSON file (located under test/java/resources/data) and with the help of an ObjectMapper instance, I load the data into the embedded DB before each test and drop the collection after it's completed:
#DataMongoTest
class UserRepositoryTest {
// the path to the JSON file
private final File USER_DATA_JSON = Paths.get("src", "test", "resources", "data", "UserData.json").toFile();
// used to load a JSON file into a list of Users
private final ObjectMapper objectMapper = new ObjectMapper();
#Autowired
private MongoTemplate mongoTemplate; // makes the interaction with the embedded MongoDB much easier
#Autowired
private UserRepository userRepository;
#BeforeEach
void setUp() throws IOException {
// deserialize the JSON file to an array of users
UserEntity[] users = objectMapper.readValue(USER_DATA_JSON, UserEntity[].class);
// load each user into embedded MongoDB
Arrays.stream(users).forEach(mongoTemplate::save);
}
#AfterEach
void tearDown() {
// drop the users collection
mongoTemplate.dropCollection("users");
}
#Test
void testFindAllSuccess() {
// WHEN
List<UserEntity> users = userRepository.findAll();
// THEN
assertEquals(2, users.size(), "findAll() should return 2 users!");
}
// other test methods
}
In my local environment, everything works just fine, no configuration is needed inside the application.properties file. But when I execute a build on Jenkins, the following error appears for all the Repository tests:
UserRepositoryTest > testFindAllSuccess() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
Caused by: java.net.UnknownHostException at InetAddress.java:1642
Caused by: java.net.UnknownHostException at Inet6AddressImpl.java:-2
The build.gradle file dependencies are declared as follows:
implementation 'org.openapitools:openapi-generator-gradle-plugin:5.0.0'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation "io.springfox:springfox-boot-starter:3.0.0"
implementation('org.modelmapper:modelmapper:2.3.0')
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'de.flapdoodle.embed:de.flapdoodle.embed.mongo'
testImplementation 'io.projectreactor:reactor-test'
compile 'io.springfox:springfox-swagger-ui:3.0.0'
annotationProcessor group: 'org.springframework.boot', name: 'spring-boot-configuration-processor'
compile 'org.mongodb:mongodb-driver-sync'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'
// https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt
implementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1'
I assume Spring Boot is not identifying the embedded MongoDB anymore. How can I configure it as simple as possible?
I saw there is a possibility of using containerized MongoDB and test it using #TestContainers, but for now I need to fix this issue since every build fails due to the tests.
LATER EDIT: By activating the --debug option in Jenkins when running the build, I discovered the following cause:
java.net.UnknownHostException: dev096.dev.cloud.******.eu: dev096.dev.cloud.******.eu: Name or service not known
Do you know if I have to add that address to the known hosts to my local machine (etc/hosts) or it should be configured locally with profiles (localhost for development and dev096.dev.cloud.******.eu for production)?
I managed to reproduce the same error locally and, if you haven't solved it yet, this is my take.
Remove all MongoDB custom configurations/properties, then add the following class to your project:
#Configuration
public class MongoTestConfig {
#Bean
MongoProperties properties() {
MongoProperties mongoProperties = new MongoProperties();
mongoProperties.setPort(33333);
mongoProperties.setHost("localhost");
return mongoProperties;
}
}
Make sure you tag your test class (UserRepositoryTest) with these three annotations:
#RunWith(SpringRunner.class)
#DataMongoTest
#Import(MongoTestConfig.class)
#DataMongoTest ignores all other bean definitions so we force the test to include the configuration that we just created using the explicit #Import.
Now the test will be forced to run on localhost. Hope it's going to work for you as it did for me! 😁
If dev096.dev.cloud.******.eu is a host used only in production, then your production server needs to know that host; not your local PC, nor Jenkins.
Ideally, you'd run your Jenkins tests using a 'jenkins' Spring profile, and then define the localhost in application-jenkins.properties.
Unfortunately, none of your solutions worked for me, but I found out later that dev096.dev.cloud.******.eu is the Jenkins instance itself.
The fix was to add an entry in /etc/hosts/ such that the server's IP to be also recognized as dev096.dev.cloud.******.eu
Related
I have a small standard Spring Boot microservice which is Spring Data REST for a single Mongo DB collection. The document contains the UUID field. The collection is a capped collection due to requirements.
Now I can build and run the app locally on my machine, no problem with that. However, we run everything in Docker on production. The container with the service is built without any issues, but once it starts, there is the following error:
{"timestamp":"2023-01-13T15:10:01.592Z","message":"Servlet.service()
for servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.core.convert.ConverterNotFoundException:
No converter found capable of converting from type [org.bson.types.Binary]
to type [java.util.UUID]] with root cause",
"component":"org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet]",
"level":"ERROR","stack_trace":
"org.springframework.core.convert.ConverterNotFoundException:
No converter found capable of converting from type [org.bson.types.Binary]
to type [java.util.UUID]
at org.springframework.core.convert.support.GenericConversionService
.handleConverterNotFound(GenericConversionService.java:322)
...
at org.springframework.data.mongodb.core.convert.MappingMongoConverter
.doConvert(MappingMongoConverter.java:1826)
...
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository
.findAll(SimpleMongoRepository.java:444)
I have several questions actually:
Basically, how to handle it? Is it possible to handle using Spring configs?
Why SimpleMongoRepository.findAll() is called during the application start?
We have several applications with Mongo DB - they are good. What's wrong with Spring Data REST in this respect?
Why is the build OK, but when the container starts it fails?
Code samples are on Groovy just like the service (everything is public by default).
The repository is described as the following
#RepositoryRestResource( collectionResourceRel = 'events', path = 'events' )
interface EventRepository extends MongoRepository<EventMessage, String> { }
The collection configuration is the following
class CustomApplicationRunner implements ApplicationRunner {
#Autowired
MongoTemplate mongoTemplate
#Autowired
ApplicationProperties configuration
#Override
void run(ApplicationArguments args) throws Exception {
mongoTemplate.writeResultChecking = WriteResultChecking.EXCEPTION
if ( !mongoTemplate.collectionExists( EventMessage ) ) {
mongoTemplate.createCollection(EventMessage, new CollectionOptions(
configuration.mongoCollectionMaxSizeBytes,
configuration.mongoCollectionMaxDocuments,
configuration.mongoCappedCollection )
)
}
}
}
In application.yml the mongo configs are (on the development side)
mongodb:
uri: mongodb://mongodb:27017/development
auto-index-creation: true
uuid-representation: STANDARD
authentication-database: admin
The Spring Boot dependencies are
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-amqp'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-integration'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Versions: SpringBoot 2.7.7, Groovy 4.0.6
Now I did a little research.
Here is the JIRA issue for Mongo DB driver to support to/from UUID conversion for both Binary and BsonBinary. However, only BsonBinary is updated, apparently it is not used.
Here is Spring Data MongoDB issue for the same problem (or very close to mine). The author provided the solution, but I wonder if it is the only way. I'd like to reach the author for more details, but they have been inactive since then.
I can implement the solution from the above, but I'd like to figure out what's exactly is going on.
Thank you all in advance!
Working further on the problem I accidentally found a solution.
There was Spring Boot Starter Spring Integration dependency. However, nothing really from Spring Integration was used in the service.
There was also Jackson2JsonObjectMapper bean defined which wasn't used anywhere as well. Likely it was a leftover from the early stages of the service. Here I should note that the data class in question was annotated by #JsonDeserializer with the specific deserializer class which worked correct.
So removing of the bean and the Spring Integration dependency resulted in resolving the issue.
I'm new to Elastic search. Started building a Spring boot application with Elastic search.
Using the latest ES version "elasticsearch-7.7.1" and for integration, I'm using below maven dependency:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.1</version>
</dependency>
Added below configuration to my spring boot app:
#Configuration
public class ESConfig {
#Bean(destroyMethod = "close")
public RestHighLevelClient client() {
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost")));
return restHighLevelClient;
}
}
Added below properties to application.yaml
elasticsearch:
host: localhost
Getting below Exception on Application startup:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.RestHighLevelClient]: Factory method 'client' threw exception; nested exception is java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
... 19 common frames omitted
Caused by: java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS
at org.elasticsearch.client.RestHighLevelClient.<clinit>(RestHighLevelClient.java:1902)
at com.sbs.communicationcontrol.search.config.ESConfig.client(ESConfig.java:14)
Can anyone please help why this exception occurred?
After some R&D, fixed the issue by adding below two dependencies:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.7.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.7.1</version>
</dependency>
I encountered the same problem when I was upgrading to org.elasticsearch.client:elasticsearch-rest-high-level-client:7.8.1 from 6.8.5. The reason behind the problem is updating elasticsearch-rest-high-level-client alone to the latest version conflicts with some of its dependent elastic search dependencies which were brought into classpath as transitive dependencies by spring-boot. When I check with the dependency tree, I found that the org.springframework.boot:spring-boot:2.3.1.RELEASE dependency brings org.elasticsearch.client:elasticsearch-rest-client:7.6.2, org.elasticsearch:elasticsearch:7.6.2 and the 7.6.2 conflicts with 7.8.1.
An Excerpt code snippet from the RestHighLevelClient citing IGNORE_DEPRECATIONS Java Docs.
public class RestHighLevelClient implements Closeable {
....
....
/**
* Ignores deprecation warnings. This is appropriate because it is only
* used to parse responses from Elasticsearch. Any deprecation warnings
* emitted there just mean that you are talking to an old version of
* Elasticsearch. There isn't anything you can do about the deprecation.
*/
private static final DeprecationHandler DEPRECATION_HANDLER = DeprecationHandler.IGNORE_DEPRECATIONS;
.....
.....
}
The error itself indicates us to update all related elasticsearch libraries, though I couldn't find any out-of-box elastic search BOM to resolve this version conflicts, I have done the below workaround.
dependencies{
implementation 'org.elasticsearch.client:elasticsearch-rest-client:7.8.1'
implementation 'org.elasticsearch.client:elasticsearch-rest-client:7.8.1'
implementation 'org.elasticsearch:elasticsearch:7.8.1'
}
//Since version 7.6.2 is selected by rule, substituting the version 7.8.1 as below
configurations.all {
resolutionStrategy {
dependencySubstitution {
substitute module('org.elasticsearch.client:elasticsearch-rest-high-level-client') with module('org.elasticsearch.client:elasticsearch-rest-high-level-client:7.8.1')
substitute module('org.elasticsearch.client:elasticsearch-rest-client') with module('org.elasticsearch.client:elasticsearch-rest-client:7.8.1')
substitute module('org.elasticsearch:elasticsearch') with module('org.elasticsearch:elasticsearch:7.8.1')
}
}
}
You are not correctly initializing your elasticsearch client, can you try with below code:
Please note that I am using the version which accepts the host, port and http scheme and it works fine for me and is the standard for creating the client.
#Configuration
#Primary
public class ElasticsearchConfig {
/**
* Creates a Elasticsearch client from config
*
* #return Elasticsearch client
*/
#Bean(destroyMethod = "close")
public RestHighLevelClient client() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9500, "http")));
return client;
}
}
And use below config
elasticsearch.host=localhost
elasticsearch.port=9500
You can set the version for all of the Spring-boot:
ext {
set('elasticsearch.version', '6.2.0')
}
to avoid overriding it in multiple places.
I am fairly new to working with Spring and I've come across a problem I cannot seem to resolve. I am trying to work with a package called Optaplanner. In this case I'm more or less following along with a simple course scheduler the video is here and the part I am working on happens at 51:00.
My problem is, one step of the process requires a dependency injection and when I build/run the Spring application I get the following error:
Description:
Field solverManager in com.java.optaplex.resource.MainResource required a bean of type 'org.optaplanner.core.api.solver.SolverManager' that could not be found.
The injection point has the following annotations:
- #javax.inject.Inject()
Action:
Consider defining a bean of type 'org.optaplanner.core.api.solver.SolverManager' in your configuration.
Process finished with exit code 1
I have used Gradle to manage my optaplanner package and I can see that the dependency is present (it is an interface called SolverManager). I cannot figure out why it cannot find/generate the bean however. I am assuming Spring would generate the bean on the fly much like a JPA repository's bean is created when using the #Autowired decorator. I have tried copying and pasting the SolverManager code to its own file under my project root and tried a few decorators on it (eg. #Component) in hopes that Spring would detect it, yet it still throws the same error and I am unsure what to do.
I have created a very simple demo app on GitHub here that has the error. The error is in the file src/main/java/com/java/optaplex/resource/MainResource.java
Also, in IntelliJ the SolverManager instance solverManager (see code below) is highlighted and says:
Could not autowire. No beans of 'SolverManager<Test, Long>' type found.
MainResource.java:
package com.java.optaplex.resource;
import com.java.optaplex.pojo.Test;
import org.optaplanner.core.api.solver.SolverManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.inject.Inject;
#RestController
#RequestMapping("/api")
public class MainResource {
// THE OFFENDING LINE IS HERE
#Inject
SolverManager<Test, Long> solverManager;
#GetMapping("/test")
public Test test () {
return new Test("Result message here");
}
}
For clarity, my Test class in the declaration of the Solver manager is:
Test.java
package com.java.optaplex.pojo;
public class Test {
private String message;
public Test(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I realize my example code doesn't actually make use of the SolverManager, I just want the error on build to stop so I can proceed developing this. I just wanted to provide a very simple case that caused the error.
Lastly, my Gradle dependencies look like this:
build.gradle:
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
id 'war'
}
group = 'com.java'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
// https://mvnrepository.com/artifact/org.optaplanner/optaplanner-core
compile group: 'org.optaplanner', name: 'optaplanner-core', version: '7.36.1.Final'
compile group: 'javax.inject', name: 'javax.inject', version: '1'
}
test {
useJUnitPlatform()
}
To make it work you just need to replace the #Inject annotation with #Autowire.
From the latest versions of Spring, the best practice is to use constructor dependency injection instead of #Autowire (the annotation is not required anymore as Spring will autowire beans automatically.
Try this:
#RestController
#RequestMapping("/api")
public class MainResource {
// Just the definition here
private SolverManager<Test, Long> solverManager;
pubilc MainResource(SolverManager<Test, Long> solverManager) {
// When Spring will start, the bean will be injected here and become
// available in this class
this.solverManager = solverManager;
}
#GetMapping("/test")
public Test test () {
// .....
}
// Other controller methods ....
}
I'm using IntelliJ, and it reports the error to me too. But I'm using the same code that I've posted in this answer and it works.
As you stated, the SolverManager bean is configured inside the optaplanner artifact, I suspect that the problem here is only the wrong annotation being used.
The IDE error bothers me too! But for the moment it works and I will leave it like this. In case I'll find a solution then I will add it here.
I am developing a API REST of route optimization with Spring Boot using OptaPlanner. I am just getting into the work with OptaPlanner and at one point I had this same problem. I had 'optaplanner-spring-boot-starter' and I added spring-boot-configuration-processor', with the idea of having the bean creation configuration that allows injecting the SolverManager in my classes, without success. Also I tried to change to other versions of OptaPlanner and without success. Finally I solved the problem adding the configuration that OptaPlanner includes in its code with the class 'RouteOptimizerConfig'. This class creates the bean of the solver, in such a way that already later I could inject it. This problem seems to be related to the fact that at a certain point the OptaPlanner SolverManager is overwritten.
Try this and add this class to your project:
#Configuration
class SolverConfig {
private final SolverFactory<VehicleRoutingSolution> solverFactory;
SolverConfig (SolverFactory<VehicleRoutingSolution> solverFactory) {
this.solverFactory = solverFactory;
}
#Bean
Solver<VehicleRoutingSolution> solver() {
return solverFactory.buildSolver();
}
}
It turns out, after a lot of online searches and digging through the Optaplanner Spring Boot packages the SolverManager bean is not provided for Spring. It seems the development focuses on the Quarkus framework.
I figured it was a good chance to try out Quarkus and once I made the change my code worked. There are some good videos on Youtube by the lead developer Geoffrey De Smet on setting up Optaplanner via Quarkus.
This is a pretty confusing one. I've read dozens of links that purport to explain how to use #Transactional but I've verified no transaction is being created.
Main.java
#SpringBootApplication
#EnableJpaRepositories(basePackages="com.mypackage")
#EnableTransactionManagement
#EntityScan(basePackages=["com.mypackage"])
#EnableJpaAuditing
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
SubscriptionController.java
#RequestMapping("/api/subscription")
#RestController
public class SubscriptionController {
#Autowired SubscriptionService subscriptionService;
Logger log = LogManager.getLogger(this.getClass().getName());
public Collection<Subscriptions> subscribe(...) {
log.info("transName: " + TransactionSynchronizationManager.getCurrentTransactionName + ", isAlive: " + TransactionSynchronizationManager.isActualTransactionActive());
return subscriptionService.getAllSubscriptions();
}
}
SubscriptionService.java
#Service
public class SubscriptionService {
#Transactional public Collection<Subscription> getAllSubscriptions() {
log.info("transName: " + TransactionSynchronizationManager.getCurrentTransactionName() + ", isAlive: " + TransactionSynchronizationManager.isActualTransactionActive());
//return subscriptions via JPQL queries here
}
}
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.RELEASE")
}
}
plugins {
id 'war'
}
apply plugin: 'org.springframework.boot'
repositories {
mavenCentral()
}
def springVersion = '5.0.3.RELEASE'
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
compile "org.springframework.security:spring-security-core:${springVersion}", exclude
compile "org.springframework.security:spring-security-config:${springVersion}", exclude
compile "org.springframework.security:spring-security-web:${springVersion}", exclude
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile "org.springframework:spring-test:${springVersion}", exclude
implementation 'org.springframework.boot:spring-boot-starter-web:2.0.5.RELEASE', exclude
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.5.RELEASE'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
compile 'org.liquibase:liquibase-core:3.6.1'
compile 'org.liquibase:liquibase-groovy-dsl:1.2.2'
}
So when I run the api call, I get null, false as the log output. The contract for #Transactional says that the transactional aspect code will be weaved into the annotated transactional method, such that there will be a transaction (and thus an entitymanager and db connection) set up before the method and closed some time afterward. But that is irrelevant becuase shouldn't spring be creating an entitymanager before the controller is run? Both things aren't working here. Neither spring, nor #Transactional, is setting up any transaction. This results in failure to do any kind of query except for what's doable via a subclasses of JpaRepository. Somehow my Jpa repositories are able to set up transactions for their own methods. But what if their results have lazily initialized properties? I need a hibernate session to get those. So I need a transaction.
Try to remove
#EnableJpaRepositories(basePackages="com.mypackage")
#EnableTransactionManagement
SpringBoot should do those things automatically
What class are you using for #Transactional?
You should use org.springframework.transaction.annotation.Transactional.
An out-of-the-box Spring-boot application using spring initializer (https://start.spring.io/) will handle transactions properly. If you make yourself a sandbox with a unit test you can observer that the transaction demarcation done in your example will produce a transaction. Here is my git hub example: https://github.com/skjenco/hibernateSandbox.git
Code:
#Test
#Transactional
public void test() {
logger.info(TransactionSynchronizationManager.getCurrentTransactionName());
.....
For transaction demarcation to work you must be in an object managed by a Spring (Component, Service, Managed Beans, etc). In the case above it appears that you are in a Spring managed service. Using a working sandbox may be helpful in trouble shooting your issue--that is what I have done to solve perplexing hibernate issues.
You may also want to post your pom.xml file. spring-data or spring-tx dependency should be added for auto configurer to create transaction manager. Otherwise explicitly create a transaction manager bean and run the code again.
You can enable TRACE level logs for org.springframework and see if transaction manager is initialized.
Also check transaction interceptor logs. Use logging.level.org.springframework.transaction.interceptor=TRACE
I plan to use Cassandra to save data reactively. To do that, I wrote the following interface:
#Repository
public interface ContributorStatRepository extends ReactiveCrudRepository<ContributorStat, Long> {
Flux<ContributorStat> findByAkonId(String akonId);
}
The exception above is thrown:
com.example.sample.controller.ContributorStatControllerTest > shouldReturnBadRequestWithBlankContributorStat FAILED
java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException
Do you know why the appropiate bean for ContributorStatRepository is not being created?
I am using Spring boot 2.0.0.M7 and these dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('javax.xml.bind:jaxb-api:2.3.0')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.boot:spring-boot-starter-data-cassandra-reactive')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('io.projectreactor:reactor-test')
}
Updated:
Running test:
#Test
public void shouldReturnBadRequestWithBlankContributorStat() throws Exception {
requestPayload = mapper.writeValueAsString(new ContributorStatDTO());
this.mockMvc.perform(post(CONTRIBUTOR_STATS_ROUTE)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(requestPayload)).andDo(print())
.andExpect(status().isBadRequest());
}
It seems you're using an #WebMvcTest annotated class to test this case (I'm not sure though, that part is missing from your question).
To test Spring WebFlux applications, you should use #WebFluxTest (see reference documentation). Even if you do, the ContributorStatRepository bean won't be there since the web test slice will only consider the web parts of your application and you usually need to mock this one with #MockBean.