Mockito with static methods in util classes - spring

I tried to find but couldnt get what i was looking for. Is it possible to do something like following in mockito?
when(TestServiceUtil.getTestItem()).thenReturn(someItem);

In your pom.xml, add the following dependencies:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
above your test class:
#RunWith(PowerMockRunner.class)
public class YourClassName
[...]
#Before
public void beforeTest() throws SQLException {
PowerMockito.mockStatic(TestServiceUtil.class);
Now you can use (as you had it):
when(TestServiceUtil.getTestItem()).thenReturn(someItem);
Last words - don't overuse PowerMockito. Focus on clean, object oriented code.

Related

The paths to the endpoints Rest API do not work when WebMvcConfigurer is enabled

A project written in Spring boom fetches data and creates some object. In the same project, a UI was made using webjars.
When I register all the necessary components for the UI properly. then the Rest endpoint paths don't work.
#Configuration
#EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/");
registry.addResourceHandler("/img/**")
.addResourceLocations("classpath:/static/img/");
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("classpath:/static/js/");
}
}
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
maybe who knows how to fix it?

Spring boot unit test are not running

I have tried many solution to fix this problem. But no luck My test cases are not running.
When i did the mvn clean package, it is running single test case.
Service layer test
#SpringBootTest
#RunWith(SpringRunner.class)
public class OrderStatusServiceTests {
#Autowired
private OrderStatusServiceImpl orderStatusService;
#MockBean
private OrderStatusRepository orderStatusRepository;
#Before
public void initialize(){
orderStatusService = new OrderStatusServiceImpl(orderStatusRepository);
}
#Test
public void saveOrderDetail(){
OrderDetail orderDetail = getOrderInformation();
Mockito.when(orderStatusRepository.save(orderDetail)).thenReturn(orderDetail);
Assert.assertEquals(orderStatusService.addOrderDetail(orderDetail), orderDetail);
}
#Test
public void getOrderDetail(){
OrderDetail orderDetail = getOrderInformation();
Mockito.when(orderStatusRepository.findByUserId("abc123")).thenReturn(java.util.Optional.of(orderDetail));
Assert.assertEquals(orderStatusService.getOrderDetail("abc123"), java.util.Optional.of(orderDetail));
}
}
Actually, the problem was with pom file.
Maven file while getting the error.
<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>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
What i did is removed the exclusion and Junit additional dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Spring boot mongodb autoconfigure throws exception "Cannot determine embedded database driver class for database type NONE"

I am using Spring boot to develop a Spring batch application. I will need my application to write the data finally to MongoDB and thus needs to configure org.springframework.data.mongodb.core.MongoTemplate for org.springframework.batch.item.data.MongoItemWriter.
My pom.xml dependency section looks like this-
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<version>${spring.batch.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jongo/jongo -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jvnet.jaxb2_commons/jaxb2-basics-runtime -->
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics-runtime</artifactId>
<version>1.11.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>de.flapdoodle.embed</groupId>-->
<!--<artifactId>de.flapdoodle.embed.mongo</artifactId>-->
<!--<version>1.50.5</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>cz.jirutka.spring</groupId>-->
<!--<artifactId>embedmongo-spring</artifactId>-->
<!--<version>RELEASE</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
The application.properties file looks like this
spring.data.mongodb.host=mongohost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=authdb
spring.data.mongodb.username=user
spring.data.mongodb.password=pwd
spring.datasource.driver-class-name=<< I don't know what to put here >>
Main class is also simple enough and looks like this-
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Now, whenever I try to run my Main class it gives out error
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
After researching a lot about this problem, I figured out that I need to let Spring know about my data store by providing the value of spring.datasource.driver-class-name in application.properties
spring.datasource.driver-class-name=com.mongodb.Server
If I provide com.mongodb.Server as my drive class name its not found on classpath and isn't recognised despite I have mongo java driver dependency on my classpath.
What should I put the value for mongoDB's driver-class-name provided I want to use mongo-java-driver?
If driver class name is not the cause of this issue, what should be the resolution of issue "Cannot determine embedded database driver class for database type NONE"mentioned in title of this question?
Try exluding DataSourceAutoConfiguration.class in your main class:
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Also you don't need this:
spring.datasource.driver-class-name
unless you need jpa configuration as well.

Spring Boot dont recognice Spring MVC

I am starting with SpringBoot, looks great, but I have some questions that I can't understand or find explained in the docs.
I created a new project with the Web, JPA, Security and MySQL dependencies. When my project is created, I go to create a #Controller class. Spring don't find #RequestMapping or ModelAndView classes.
I guessed that use the Web module of SpringBoot will add all the necessary dependencies to use SpringMVC (I read some examples and none add extra dependencies) and all work great with MVC.
These are my dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-groovy-templates</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
</dependencies>
Other example, is the WebMvcConfigurerAdapter (from spring-mcv) class that I can't resolve:
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
This class is from, but I don't see Springboot include this dependy:
org.springframework
spring-webmvc
Maybe I am wrong and read some post that center all the info in Spring Boot, but don't show manual config in the poms.
WebApplication class (Auto Generated):
#SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
ServletInitializer.java class (Auto generated)
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class);
}
}
Looks like my maven local repository is corrupted.
I was using these libraries in other projects and all works fine. Sorry for the time wasted. Anyway, I let the response for some users with similar problems.

Bind a String value to an enum in a #RequestBody entity in Spring Boot

I am using Spring Boot to write a web service. I have an entity Animal and an enum Kind that can be either Kind.DOG or Kind.CAT. The Animal class contains private Kind kind as one of its instance variables. When I make an HTTP request, I pass in a string value for kind and when the request maps to the header:
#RequestMapping(method=RequestMethod.POST, value="/create")
public ResponseEntity<Animal> createAnimal(#RequestBody Animal animal)
I want kind to be internally converted to Kind.DOG/Kind.CAT if I am passed in either "dog" or "cat". Right now, if I pass in DOG or CAT, it works fine but if's lowercase it doesn't. Can someone tell me what to do? I tried the following:
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Kind.class, new KindEnumConverter());
}
#RequestMapping(method=RequestMethod.POST, value="/create")
public ResponseEntity<Animal> createAnimal(#RequestBody Animal animal)
and
public class KindEnumConverter extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(Kind.valueOf(text.toUpperCase()));
}
}
but it didn't work.
InitBinder won't work with #RequestBody as per my experience.
We use Spring Boot and the way I solved this problem is, I excluded all the jackson related dependencies from spring-boot-starter-web, so that I can use latest jackson.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</exclusion>
</exclusions>
</dependency>
And then I added the latest jackson dependencies as:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.1</version>
</dependency>
Now that we have the new jackson library we can just set this in the application.properties file:
spring.jackson.mapper.accept_case_insensitive_enums=true
In case you use YAML, then:
spring:
jackson:
mapper:
accept_case_insensitive_enums: true
Inspiration: https://stackoverflow.com/a/44217670/1781024

Resources