Unit Test: Mocking SpringBootApplication main class with SpringApplication.run - spring

I have been working on this for long and could not figure out a way in mocking the main class in my Spring Boot application (with the code as provided below); without directly calling the actual class in my test class (which I need to avoid).
I've tried with Power Mockito and MockRunner, but doesn't seem to work. How can I proceed?
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
#SpringBootApplication(exclude = KafkaAutoConfiguration.class)
public class KafkaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaConsumerApplication.class, args);
}
}
P.S. I'm furnishing the original test class I've written for the same, which is not appropriate way to test
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = KafkaConsumerApplication.class)
#ActiveProfiles("dev")
public class KafkaConsumerApplicationTest {
#Test
public void contextLoads() {
}
}

Related

#Scheduled works in Spring Boot application but not in #SpringBootTest

What is the reason that the #Scheduled function runs in Spring Boot Application but not in test environment (#SpringBootTest) ?
I am following the tutorial at https://github.com/spring-guides/gs-scheduling-tasks, the repository's test runs fine, but mine #Scheduled function does not run for once in my test, although it is working fine in my Spring Boot application.
Is it because of the version of Junit (The tutorial is using Junit5 while I am using JUnit 4) ?
My purpose of this test is to check the correctness of the configuration of my scheduler.
Below is the code I replicated with difference in Junit version.
BootApplication.java
package com.itsedo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
// SecurityAutoConfiguration: exclude default spring security boot file.
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
#ComponentScan("com.itsedo")
#EnableScheduling
public class BootApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BootApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(BootApplication.class, args);
}
}
ScheduledTasks.java
package com.itsedo.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
#Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
File ScheduledTasksTest.java
package com.itsedo.test;
import org.awaitility.Duration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.verify;
import com.itsedo.scheduler.ScheduledTasks;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ScheduledTasksTest {
#SpyBean
ScheduledTasks tasks;
#Test
public void reportCurrentTime() {
await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> {
verify(tasks, atLeast(2)).reportCurrentTime();
});
}
}
Test Output
Running Spring Boot application

Spring Boot did not Autowiring

Can someone tell me please what I'm doing wrong, I'm trying to develop a little application but I just simply can't Autowire a class in the controller, I have been researching and I Know that for Autowire works, my class must be in a child package of my #SpringBootApplication annotation, or I should specify in #ComponentScan annotation the package of my class, but no matters what I do I still getting the same error:
This is my project structure:
package net.spring.auditoria;
import org.springframework.boot.SpringApplication;T
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AuditoriaApplication {
public static void main(String[] args) {
SpringApplication.run(AuditoriaApplication.class, args);
}
}
Controller:
package net.spring.auditoria.bll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class AuditoriaController {
#Autowired
private AuditoriaManagement am;
private final Logger LOGGER = LoggerFactory.getLogger(AuditoriaController.class);
#GetMapping("/auditar")
public String auditar() {
LOGGER.info("auditar()");
return "main";
}
}
https://github.com/jlpm-mex/auditoria
Because AuditoriaManagement is not a Spring bean or component.

java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...)

Hey i have started learning spring-boot junit testing using spring boot Test framework at the time of creating the test case i am facing issues below .
how to resolve this issue.
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:70)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:137)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
this is my RentalCarSystemApplicationTests.java
package com.test.project.rentalcarsystem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class RentalCarSystemApplicationTests {
#Test
public void contextLoads()
{
}
}
this is my TestWebApp.java
package com.test.project.rentalcarsystem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.web.context.WebApplicationContext;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
public class TestWebApp extends RentalCarSystemApplicationTests {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testEmployee() throws Exception {
mockMvc.perform(get("/car")).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.setMilleage").value("24")).andExpect(jsonPath("$.setModelname").value("BMW"))
.andExpect(jsonPath("$.setSeating_capacity").value("5")).andExpect(jsonPath("$.setType").value("SUV"))
.andExpect(jsonPath("$.setCost").value("3000")).andExpect(jsonPath("$.setEmail").value("demo#gmail.com"))
.andExpect(jsonPath("$.setNumber").value("9845658789")).andExpect(jsonPath("$.setPincode").value(560036));
}
}
From the error logs it gives hint to use classes attribute for #SpringBootTest so
Change #SpringBootTest to #SpringBootTest(classes = Application.class)
Give a fully classified name of the class like below.
#SpringBootTest(classes=com.package.path.class)
Also refer this thread

Field ** in com.** required a bean of type 'com.**' that could not be found

I'm following this tutorial and I'm having some trouble starting my application.
When I run mvn spring-boot:run in the backend folder I get the following error:
Field movieRepository in com.movieseat.services.impl.MovieServiceImpl required a bean of type 'com.movieseat.repositories.MovieRepository' that could not be found.
MovieServiceIml.java
package com.movieseat.services.impl;
// Java imports
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// Spring imports
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Project imports
import com.movieseat.models.Movie;
import com.movieseat.services.MovieService;
import com.movieseat.repositories.MovieRepository;
#Service
public class MovieServiceImpl implements MovieService {
#Autowired private MovieRepository movieRepository;
#Override public List<Movie> getAllmovies() {
List<Movie> movies = new ArrayList<Movie>();
Iterator<Movie> iterator = movieRepository.findAll().iterator();
while (iterator.hasNext()) {
movies.add(iterator.next());
}
return movies;
}
}
MovieRepository.java
package com.movieseat.repositories;
// Java imports
import java.io.Serializable;
// Spring imports
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
// Project imports
import com.movieseat.models.Movie;
#Repository
public interface MovieRepository extends CrudRepository<Movie, Serializable> {}
The following structure is used:
com
movieseat
Application.java
controllers
MovieController.java
models
MovieModel.java
repositories
MovieRepository.java
services
impl
MovieServiceImpl.java
MovieService.java
And this is my Application.java:
package com.movieseat;
// Spring importss
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan({"com.movieseat.*"})
#EnableJpaRepositories("com.movieseat.repositories.*")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
My thought is that using #EnableJpaRepositories("com.movieseat.repositories.*") would make all repositories accessible. But I'm doing something wrong.
Try it without * (wildcard),
#EnableJpaRepositories("com.movieseat.repositories")
Make sure you have the #Entity annotation on your Movie.

Spring Boot AOP #before not working

I have written this code :
It seems perfect but not working
When i run the code it runs fine
I hit the URL for (/) and only the greetings method is called
AOP method is not getting called
This is my main Class
DemoApplication.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aop.AOPSample;
com.services.TaskService;
#SpringBootApplication
#ComponentScan({"com.aop","com.services"})
#RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/")
public void greetings(){
new TaskService().startService();
System.out.println("In Greetings");
}
}
AOPSample.java
package com.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class AOPSample {
#Before("execution(public void com.services.TaskService.startService())")
public void beforeSampleCreation() {
System.out.println("Hello world");
}
}
TaskService.java
package com.services;
public class TaskService {
public void startService(){
}
public void endService(){
}
}
Output:
In Greetings

Resources