I want to use the #Slf4j annotation, so I imported this dependency in my pom.xml file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.29</version>
</dependency>
but I have the error Cannot resolve symbol Slf4j
#Service
#Slf4j
#Transactional(readOnly = true)
public class PasswordResetTokenService {
..
}
The annotation #Slf4j is a Lombok annotation and is not present in the slf4j dependency.
If you want to use this annotation instead of declaring a logger field, you will need to add an extra dependency to Lombok:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
In case of Spring Boot, the parent POM might already specify the version. Then you don't need to declare the specific version anymore.
See:
https://projectlombok.org/features/log
https://projectlombok.org/api/lombok/extern/slf4j/Slf4j.html
I believe #Slf4j annotation is not actually coming from Slf4j but from Lombok. please look at this link that seems to provide a very good template to start from https://howtodoinjava.com/spring-boot2/logging/logging-with-lombok/
if you look at the excerpt of Application.java. the import for the annotation is coming from lombok
import lombok.extern.slf4j.Slf4j;
Related
Im having a Springboot project where I have found a way to create and run simple Junit testcase which looks into a repository and fetches some data attribute for a given entity. The result of the Junit run is pass so no problem in regards to that.
But the thing is here, that I have seen a lot of examples out there where tutorials are showing Springboot projects where they can simply run Junit tests with only #Runwith or #SpringBootTest
for their specific test classes.
In my case I have to add 3 annotations, #SpringBootTest, #RunWith as well as #ContextConfiguation(with parameters) until Im able to run the testcase.
So my question is how will I be able to run it as minimalistic as possible, (some exercises I have seen have only one annotation for their springboot test class)
My Springboot test class looks like this:
Screenshot of my Junit class
and my Directory structure looks like this:
Screenshot of my Project directory structure
My application.properties looks like this:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/erfan
spring.datasource.username=erfan
spring.datasource.password=
#Some additional properties is trying to be set by Spring framework so this must be set
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
#spring.datasource.initialization-mode=always
#spring.datasource.initialize=true
#spring.datasource.schema=classpath:/schema.sql
#spring.datasource.continue-on-error=true
#HikariCP is a ConnectionPool manager, related to DB stuff
#Below is the property key you need to set to * as value to expose all kind of monitoring related information
#about your web application
#management.endpoints.web.exposure.include=*
And my 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 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.1.1.RELEASE</version>
</parent>
<groupId>com.sample</groupId>
<artifactId>postgres</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>postgres</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
So am I missing like something in my application.properties file? Something that I should include to be able to remove "boilerplate" annotation in my test class?
Depends on what you're trying to do. Basically spring has custom annotations that configures the spring context to include only relevant beans. This is the so called test slices.
But there are a few "rules" I always try to follow:
Avoid #SpringBootTest unless you're doing integration testing, or manually setting which classes to use #SpringBootTest(classes = {MyService1.class, MyService2.class}
If you're testing spring jpa, you can use the #DataJpaTest annotation, example here
If you're testing controllers you can use the #WebMvcTest, example here
If you're testing other services, you can always use #ContextConfiguration to configure the spring context accordingly.
So for example, for your test I would write it in one of two ways:
#RunWith(SpringRunner.class)
#DataJpaTest
#Import(AnotherConfig.class)
class MyTest {
// test stuff here
}
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {AnotherConfig.class})
// NOTE, if you have a JpaConfig class where you #EnableJpaRepositories
// you can instead add this config class to the #ContextConfiguration classes
#EnableJpaRepositories
class MyTest {
// test stuff here
}
Basically, don't worry about how many annotations you have on top of your test, but worry about which beans/services are being autowired. For example the #SpringBootTest is a single annotation, but autowires all the beans in the spring context.
I strongly recommend not using a bunch of spring annotations on unit tests. Unit tests should only test one piece of code and not relate with externals or other layers, so Mockito should be sufficient.
Example:
#RunWith(MockitoJUnitRunner.class)
public class FooTest {
#InjectMocks
private FooService service;
#Mock
private FooRepository repository;
#Test
public void whenHappyPath_shouldReturnTrue(){
doReturn(Optional.empty()).when(repository).findById(anyLong());
assertTrue(service.isFoo(1L));
}
}
You are preventing your unit test to reach the repository layer, so you don't need to create a context with embedded DB or any other thing.
If you are using for integration tests then it is different and you will need different strategies. For that, I'd recommend use embedded DB on tests (which is made by default if you have h2 dependency):
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
And also use a integration or test spring profile:
#ActiveProfile("test") // or integration, you choose
public class FooIntegrationTest{
...
}
or force other configuration file to point to another configuration
#TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
application-test.properties
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
Erfan, it completely depends on your test scenario.
First Scenario : Complete test (Integration Test)
If you want to test the whole of your app, like testing the Service layer, Repository layer, and the Controller layer, you need a real spring-context, so you must use all #SpringBootTest and #RunWith and ... to initialize spring context to test whole layers.
(This called integration-test)
Unit Test vs Integration Test: What's the Difference
how-to-use-java-integration-testing
Second Scenario: Unit test
If you want just to test a piece of your code, just like you want to test just service layer and other layers (like repository) does not important in your scenario, in this situation you must use some new framework like Mockito, to mock the pieces that you don't want to test them, in these scenarios you don't need the **spring-context initialization ** so you don't need to use #SpringBootTest or other annotations.
Mockito Sample
So based on your scenario you can use those annotations.
I strongly recommend you to read the below link for further information about best practices for testing in java.
Modern Best Practices for Testing in Java
I have a Spring MVC project which does NOT USE spring-boot.
Im trying to use Jackson2ObjectMapperBuilderCustomizer in my appConfig class to configure a default date format.
I have these two dependencies in already but I'm still getting an error on the ObjectMapper? I am using spring version 4. All the examples for using the Jackson2ObjectMapperBuilderCustomizer are using spring boot which seems to not need need a dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>`
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>`
The class is only part of Spring Boot dependencies. If you are determined to not use any Spring Boot dependencies, you will have to look for alternatives, otherwise you can use the following:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
Add jackson-datatype-jsr310 dependency . its an alternative for non spring boot projects.
https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310/2.10.1
I made up an example spring boot project running with Vaadin (latest version). I only have one view:
#Route
public class MainView extends VerticalLayout {
The UI was working like a charm, then I had to refactor the project in modules.
I put the SpringBootApplication in a module and Vaadin in another one. I'm getting into modules, so I don't know exactly how they interact, but I had to put the dependency in the boot pom to the vaadin pom in order to let it start.
Now it is not working, when I call localhost it says
Could not navigate to ''
Reason: Couldn't find route for ''
Available routes:
This detailed message is only shown when running in
development mode.
The spring boot application:
#SpringBootApplication
#ComponentScan(basePackages = {"my.app"})
#EntityScan(basePackages = {"my.app"})
#EnableJpaRepositories(basePackages = {"my.app"})
#EnableJpaAuditing
public class LicensemanagerApplication
boot module pom.xml dependency snippet:
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>app_frontend</artifactId>
<version>${project.version}</version>
<scope>runtime</scope>
</dependency>
app_frontend module pom.xml dependency snippet:
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
.............
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>13.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Vaadin by default only looks for #Route annotated classes within the same package that contains the #SpringBootApplication annotation. To make it look in other packages, you need to pass those as the value to the #EnableVaadin annotation, e.g. #EnableVaadin({"my.app"}).
I have removed the #EnableSwagger2 & io.springfox:springfox-swagger2 dependency so as to not use the traditional swagger related annotations and instead use a JSON file.
I have changed the Swagger from annotations based to JSON based using the details shared here : Overcoming Swagger Annotation Overload by Switching to JSON
But now it is showing
Can someone help me with what may be causing the issue?
I think you have not added the swagger dependency in the Pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
I think might be this can be the reason it is not opening the Swagger UI.
Please try to create the bean in the configuration file so that swagger can run it properly.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.cloud")))
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.data.rest.webmvc")))
.paths(PathSelectors.any()).build();
}}
I am trying to write a test following this documentation:
https://doc.akka.io/docs/akka/current/fsm.html#overview
This looks like to extend the AbstractJavaTest I need the scalatest dependency so I added the following to my pom:
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
From more googling I found that this class only extends the JUnitSuite, I am able to import it in my class, but I cant seen to extend it
THis works
import org.scalatest.junit.JUnitSuite;
But this doesn't
public class MyTest extends JunitSuite {}
How do I get the JunitSuite class?
You picked a truly antediluvian version of ScalaTest from 2010, whereas your Akka version is very recent.
Just go to Maven Central, scalatest and pick some newer version, you could try for example
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.12</artifactId>
<version>3.2.0-SNAP10</version>
<scope>test</scope>
</dependency>
Just make sure that you use either 2.11 or 2.12 consistently.