All Questions
Tagged with spring-boot junit
2,355
questions
266
votes
4
answers
160k
views
Difference between @Mock, @MockBean and Mockito.mock()
When creating tests and mocking dependencies, what is the difference between these three approaches?
@MockBean:
@MockBean
MyService myservice;
@Mock:
@Mock
MyService myservice;
Mockito.mock()
...
237
votes
16
answers
290k
views
Unable to find a @SpringBootConfiguration when doing a JpaTest
I'm trying to run a simple Junit test to see if my CrudRepositories are indeed working.
The error I keep getting is:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration ...
103
votes
13
answers
178k
views
How to test main class of Spring-boot application
I have a spring-boot application where my @SpringBootApplication starter class looks like a standard one. So I created many tests for all my functionalities and send the summary to sonarqube to see my ...
90
votes
14
answers
192k
views
How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?
I tried:
@RunWith(SpringJUnit4ClassRunner.class)
@EnableAutoConfiguration(exclude=CrshAutoConfiguration.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public ...
85
votes
3
answers
73k
views
SpringRunner vs SpringBootTest
In unit test, what are the differences between @Runwith(SpringRunner.class) & @SpringBootTest?
Can you explain to me the use cases of each one?
83
votes
4
answers
98k
views
reason: no instance(s) of type variable(s) T exist so that void conforms to using mockito
I want to throw an Exception when running a void method
when(booking.validate(any())).thenThrow(BookingException.builder().build());
but I have a compilation error:
Required type: T
Provided: void
...
83
votes
5
answers
134k
views
How to write a unit test for a Spring Boot Controller endpoint
I have a sample Spring Boot app with the following
Boot main class
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(...
74
votes
5
answers
61k
views
What is the proper annotation since @SpringApplicationConfiguration, @WebIntegration, is deprecated in Spring Boot Framework?
What is the proper annotation since @SpringApplicationConfiguration and @WebIntegration are deprecated as of Spring Boot Framework 1.4? I'm trying to play around with unit testing.
72
votes
13
answers
149k
views
Spring Boot properties in 'application.yml' not loading from JUnit Test
What am I doing wrong? I'm using this little standalone App which runs and finds my src/main/resources/config/application.yml. The same configuration doesn't work from JUnit, see below:
@...
69
votes
1
answer
103k
views
How to test a component / bean in Spring Boot
To test a component/bean in a Spring Boot application, the testing part of the Spring Boot documentation provides much information and multiple ways :
@Test, @SpringBootTest, @WebMvcTest, @DataJpaTest ...
66
votes
21
answers
222k
views
How do I mock a REST template exchange?
I have a service in which I need to ask an outside server via rest for some information:
public class SomeService {
public List<ObjectA> getListofObjectsA() {
List<ObjectA> ...
62
votes
7
answers
149k
views
Spring boot autowiring an interface with multiple implementations
In normal Spring, when we want to autowire an interface, we define it's implementation in Spring context file.
What about Spring boot?
how can we achieve this?
currently we only autowire classes ...
58
votes
5
answers
131k
views
@Value "Could not resolve placeholder" in Spring Boot Test
I want to take a Junit test for Spring-boot as below:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationTest.class})
public class TestOnSpring {
@Value("${app....
49
votes
7
answers
79k
views
How to test Spring @Scheduled
How do I test @Scheduled job tasks in my spring-boot application?
package com.myco.tasks;
public class MyTask {
@Scheduled(fixedRate=1000)
public void work() {
// task execution ...
46
votes
6
answers
39k
views
How to properly convert domain entities to DTOs while considering scalability & testability
I have read several articles and Stackoverflow posts for converting domain objects to DTOs and tried them out in my code. When it comes to testing and scalability I am always facing some issues. I ...
43
votes
7
answers
152k
views
@TestPropertySource doesn't work for JUnit test with AnnotationConfigContextLoader in Spring 1.2.6
It doesn't seem that anything I do in Spring 4.1.17 with Spring Boot 1.2.6.RELEASE works at all. I just want to access the application properties and override them with test if necessary (without ...
39
votes
6
answers
59k
views
spring-boot-starter-test with JUnit 5
Using spring-boot-starter-test as of 2.0.6 brings in a JUnit 4 dependency. How can I use spring-boot-starter-test (via Gradle), but use JUnit 5 instead, without the JUnit 4 dependency being pulled in?...
38
votes
3
answers
44k
views
Difference between junit-vintage-engine and junit-jupiter-engine?
It's a two-fold question.
What is the difference between junit-vintage-engine and junit-jupiter-engine?
SpringBoot starter projects come with an exclusion for junit-vintage-engine. Is it to enforce ...
30
votes
5
answers
34k
views
JUnit @BeforeClass non-static work around for Spring Boot application
JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.
I want to clean up a database ...
28
votes
4
answers
36k
views
Spring Boot MVC Test - MockMvc is always null
I'm trying to write my first Spring MVC test but I just cannot get Spring Boot to inject the MockMvc dependency into my test class. Here is my class:
@WebMvcTest
public class WhyWontThisWorkTest {
...
27
votes
2
answers
33k
views
What is the use of contextLoads method in Spring Boot Junit Testcases?
This method is empty in all my JUnit test cases. What is the use of this method?
Sonarqube is complaining
"Add a nested comment explaining why this method is empty, throw an ...
26
votes
3
answers
25k
views
MockRestServiceServer: how to mock a POST call with a body?
I am trying to mock a POST method with MockRestServiceServer in the following way:
MockRestServiceServer server = bindTo(restTemplate).build();
server.expect(requestTo("/my-api"))
.andExpect(...
25
votes
3
answers
13k
views
SpringBoot @WebMvcTest, autowiring RestTemplateBuilder
I've got a problem while testing a Spring Controller.
I'm using the annotation @WebMvcTest in my test class.
When I run the test, I get this error:
No qualifying bean of type 'org.springframework.boot....
25
votes
4
answers
40k
views
Connection refused when using wiremock
I have this piece of code in a Junit, where I clearly set the port to 8888
when(clientUtils.getLinkUrl(eq(HOSTELS_MICROSERVICE.name()), eq(HOSTELS_MICROSERVICE.name()), anyMap()))
....
25
votes
1
answer
40k
views
How to make Spring's @Autowired to work in JUnit 5 extensions? [duplicate]
I have a Spring Boot application, and I am trying to use @Autowired in a JUnit 5 extension. However, I cannot get it to work. (The @Autowired field is null.) Can anybody help?
Below is code that ...
22
votes
8
answers
40k
views
Using junit test to pass command line argument to Spring Boot application
I have a very basic Spring Boot application, which is expecting an argument from command line, and without it doesn't work. Here is the code.
@SpringBootApplication
public class Application ...
21
votes
1
answer
33k
views
Spring boot test: context loaded for every test?
In my project we have a super class for all our tests. This is the signature of that class
@RunWith(SpringRunner.class)
@SpringBootTest(value = {"management.port=0"}, classes = Application.class, ...
20
votes
11
answers
26k
views
Unit testing of Spring Boot Actuator endpoints not working when specifying a port
recently I changed my spring boot properties to define a management port.
In doing so, my unit tests started to fail :(
I wrote a unit test that tested the /metrics endpoint as follows:
@RunWith (...
20
votes
1
answer
44k
views
How can I mock db connection in Spring Boot for testing purpose?
Situation:
I am using Spring Cloud with Spring Boot in a microservice, that microservice is loading a DB config information to configure a connection.
I created a test to get the rest interfaces ...
20
votes
1
answer
15k
views
IntelliJ: How to set log levels for tests
I have a problem with test console output in IntelliJ 2016.
When I run JUnit tests via IntelliJ, the console window is flooded with enormous amounts of log lines, for example
DEBUG reactor.ipc ....
...
19
votes
4
answers
39k
views
Is there any special configuration to use SpringRunner with junit5? [duplicate]
My micro-service project based on spring-boot framework and all my unit test running with spring runner.
@RunWith(SpringRunner.class)
adding this annotations, imports the following library:
import ...
19
votes
2
answers
15k
views
JUnit 5: Inject spring components to Extension (BeforeAllCallback / AfterAllCallback)
tl;dr: How can I instantiate a custom data provider as a Spring component before all tests run?
Is there a smart way to inject Spring components into a custom JUnit Jupiter extension that implements ...
18
votes
2
answers
11k
views
Integration test with TestRestTemplate for Multipart POST request returns 400
I know that similar question has been here already couple of times but following suggested fixes did not solve my problem.
I have a simple controller with the following endpoint:
@RequestMapping(...
18
votes
3
answers
15k
views
Spring Boot / JUnit, run all unit-tests for multiple profiles
I have a BaseTest class which consists of several tests. Each test shall be executed for EVERY profile I list.
I thought about using Parameterized values such as:
@RunWith(Parameterized.class)
@...
17
votes
2
answers
16k
views
Spring boot and Flyway: Clear database data before integration tests
I'm building a REST service using Spring boot framework (v2.0.2), where I have integration tests running on a database. I googled a lot and there is a sea of articles about cleaning database before ...
16
votes
8
answers
18k
views
Getting java.lang.AbstractMethodError when I test using REST Assured
I'm trying to test a REST api defined in my controller class using REST Assured v4.3.0, but I get java.lang.AbstractMethodError when I run the test. I understand this error is occurring because I'm ...
16
votes
2
answers
30k
views
How to JUnit Test Spring-Boot's Application.java
Apologize as this might seems to be an useless act, but is there any way we can actually do junit test on Spring-Boot(1.3.8.RELEASE)'s Application.java which this class does nothing but to start a ...
16
votes
5
answers
21k
views
@WebMvcTest fails with java.lang.IllegalStateException: Failed to load ApplicationContext
I'm having trouble getting my tests annotated with @WebMvcTest to work. I have also configured spring-cloud-config-server and spring-cloud-starter, and all Test classes with this annotation seem to ...
16
votes
3
answers
10k
views
What is the best way to test that a spring application context fails to start?
I use the spring-boot-starter-web and spring-boot-starter-test.
Let's say I have a class for binding configuration properties:
@ConfigurationProperties(prefix = "dummy")
public class DummyProperties ...
16
votes
1
answer
6k
views
@RabbitListener method testing in SpringBoot app
Code:
RabbitMQListener:
@Component
public class ServerThroughRabbitMQ implements ServerThroughAMQPBroker {
private static final AtomicLong ID_COUNTER=new AtomicLong();
private final long ...
15
votes
1
answer
10k
views
Transactions in spring boot testing not rolled back
I have an integrations test class for my UserController. The contents of the following class are:
// imports...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(...
14
votes
3
answers
26k
views
Gradle 5 JUnit BOM and Spring Boot Incorrect Versions
I am using Gradle 5's BOM (Bill of Materials) feature. This is how I describe it for my JUnit 5 dependencies:
testImplementation(enforcedPlatform("org.junit:junit-bom:5.4.0")) // JUnit 5 BOM
...
14
votes
2
answers
16k
views
Spring Boot JPA metamodel must not be empty! when trying to run JUnit / Integration Tests
Am using Spring Boot, JUnit 4 & Mockito in a maven based project to tests my Spring Boot Microservice REST API.
So, on startup, the DataInserter class loads data from owner.json and cars.json.
...
14
votes
1
answer
4k
views
@IfProfileValue not working with JUnit 5 SpringExtension
I use junit5 with spring-starter-test, in order to run spring test I need to use @ExtendWith instead of @RunWith. However @IfProfileValue work with @RunWith(SpringRunner.class) but not with @...
14
votes
1
answer
10k
views
Spring Boot integration tests: @AutoConfigureMockMvc and context caching
I'm building very basic web application using Spring Boot 1.5.1 and wanted to create integration tests for checking REST endpoints.
As recomended by documentation, MockMvc might be used for it.
Here ...
13
votes
3
answers
4k
views
How to hide spring boot banner.txt in junit test with SpringJUnit4TestRunner?
When I configure an Spring Boot Application, I can disable the banner via run configuration in the static main method. So far so good.
But what if I have the following:
@RunWith(...
13
votes
3
answers
62k
views
How to test POST method in Spring boot using Mockito and JUnit
I am newbie to Unit testing using JUnit and Mockito in Spring boot framework.
I want to test this method. How to test POST Request method:
// add Employee
@RequestMapping(method = RequestMethod.POST)
...
13
votes
5
answers
9k
views
Spring Boot Test MalformedURLException: unknown protocol: classpath
If java.net.URL is used in a Spring Boot application, with classpath protocol, it works as expected, because Spring Boot registers URLStreamHandlerFactory. e.g. new URL("classpath: someFile.whatever")....
13
votes
2
answers
5k
views
Integration testing Spring Boot based Microservices
I have read many of the guides about working with Spring Boot and RESTful services, and many of them contain information about running unit tests, most notably "Building an Application with Spring ...
12
votes
4
answers
49k
views
RESTful Services test with RestTemplate
In my application I have a lot of REST- Services. I have written tests for all services with:
org.springframework.web.client.RestTemplate
A REST- Service invokation e.g. looks like this:
final ...