Can't run JUnit test with Spring - spring

I have a test class looking like this:
#RunWith(SpringRunner.class)
#SpringBootTest
public class myTests {
#Autowired
private MyComponent myComponent;
#Test
public void test1() { ... }
}
I get an initialization error and an exception:
java.lang.Exception: No tests found matching...

Take a look at your imports; for your code to work in the way you intend it to, your imports should include:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
but depending on how your IDE is configured you can sometimes end up with a different version of junit by default which doesn't play nicely with Spring Boot.
If the above imports don't work for you you may need to add the following maven dependency to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Related

Required: Definitive Annotations and pom dependencies to test Apache Camel with Spring Boot and Java Config

I'm going round in circles with this one.
Because it uses Spring Test and Java Config, I copied the simple FilterTest example from here, which worked OK as was.
But as soon as I added an #Autowired field, I got an UnsatisfiedDependencyException [Unsatisfied dependency expressed through field ... No qualifying bean of type ... available].
After fixing that I now get a NullPointerException on resultEndpoint.expectedBodiesReceived(expectedBody); in the first #Test method. When this happens, there is absolutely no output in the console, so evidently Spring hasn't even started.
Here's the slightly modified test class:
package org.apache.camel.spring.javaconfig.patterns;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.javaconfig.SingleRouteCamelConfiguration;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import c10y.camel.converter.QbInvoiceConverter;
/**
* Tests filtering using Spring Test and Java Config
* page: https://camel.apache.org/manual/latest/testing.html
* code: https://github.com/apache/camel/blob/master/core/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java
*/
#CamelSpringBootTest
#ContextConfiguration
#DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public class FilterTest {
#EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
#Produce("direct:start")
protected ProducerTemplate template;
#Autowired
private QbInvoiceConverter converter;
#Test
public void testSendMatchingMessage() throws Exception {
String expectedBody = "<matched/>";
resultEndpoint.expectedBodiesReceived(expectedBody);
template.sendBodyAndHeader(expectedBody, "foo", "bar");
resultEndpoint.assertIsSatisfied();
}
#Test
public void testSendNotMatchingMessage() throws Exception {
resultEndpoint.expectedMessageCount(0);
template.sendBodyAndHeader("<notMatched/>", "foo", "notMatchedHeaderValue");
resultEndpoint.assertIsSatisfied();
}
#Configuration
public static class ContextConfig extends SingleRouteCamelConfiguration {
#Bean
public RouteBuilder route() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.filter(header("foo")
.isEqualTo("bar"))
.to("mock:result")
;
}
};
}
}
}
I have tried to bring this up to date with the migration instructions here. Briefly, this states:
Migration steps linked to JUnit 5 support in Camel Test itself should have been applied first
Imports of org.apache.camel.test.spring.* should be replaced with org.apache.camel.test.spring.junit5.*
Usage of #RunWith(CamelSpringRunner.class) should be replaced with #CamelSpringTest
Usage of #BootstrapWith(CamelTestContextBootstrapper.class) should be replaced with #CamelSpringTest
Usage of #RunWith(CamelSpringBootRunner.class) should be replaced with #CamelSpringBootTest
The other part of my question relates to having the correct dependencies in pom.xml. I'm learning Camel from Camel in Action E2, so my pom has test dependencies from the book as well as others I have picked up on the way; so there may be clashes or incompatibilities in there:
<!-- from .../camel-in-action-2/chapter9/spring-boot-test-one-route/pom.xml -->
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
</dependency>
<!-- testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-spring</artifactId>
<scope>test</scope>
</dependency>
<!-- from elsewhere -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-spring-junit5</artifactId>
<scope>test</scope>
</dependency>
I'm using Apache Camel 3.4.0 LTS and Spring Boot 2.3.0.RELEASE.
As the title to this question states, I'd really like to have the definitive annotation and pom configuration to allow me to simply get on with creating test routes to unit test my Components, Converters, and so forth [without tearing my hair out!].
PS: What's the difference between org.junit.Test and org.junit.jupiter.api.Test annotations, and when should you use one over the other?

Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration

we are using Freemarker for generating the HTML code for the emails our application is going to be sending.
Our usage and configuration is based off of https://github.com/hdineth/SpringBoot-freemaker-email-send
Particularly:
package com.example.techmagister.sendingemail.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import java.io.IOException;
#Configuration
public class FreemarkerConfig {
#Bean(name="emailConfigBean")
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates/");
return bean;
}
}
However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using JUnit 5.
When I added the relevant dependencies
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
versions:
<junit.jupiter.version>5.3.1</junit.jupiter.version>
<mockito.version>2.23.0</mockito.version>
And made a test class:
package com.example.techmagister.sendingemail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
#ExtendWith({SpringExtension.class, MockitoExtension.class})
#Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() throws Exception {
try {
Template template = emailConfig.getTemplate("email.ftl");
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run that in debug mode, emailConfig is null.
Why is that?
Their test example https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java
works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.
In our actual code (which is large, multi module project), I have another error org.springframework.beans.factory.UnsatisfiedDependencyException
caused by:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.
You cannot autowire your emailConfigBean directly as a freemarker.template.Configuration
FreeMarkerConfigurationFactoryBean is a factorybean.
To get the Confuguration you need to call factorybean.getObject()
so instead of
#Autowired
#Qualifier("emailConfigBean")
private Configuration emailConfig;
just autowire your factorybean FreeMarkerConfigurationFactoryBean and load your template with emailConfig.getObject().getTemplate("email.ftl")
#Autowired
#Qualifier("emailConfigBean")
private FreeMarkerConfigurationFactoryBean emailConfig;
#Test
void testFreemarkerTemplate(){
Assertions.assertNotNull(emailConfig);
try {
Template template =
emailConfig
.getObject() // <-- get the configuration
.getTemplate("email.ftl"); // <-- load the template
Assertions.assertNotNull(template);
} catch (Exception e) {
e.printStackTrace();
}
working test on github
On the other hand...
In a Spring Boot application the Freemarker configuration can be simplified by using the spring-boot-starter-freemarker dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
This starter for building MVC web applications using FreeMarker views adds the necessary auto-configuration. All you need to do is placing your template files in the resources/templates folder.
Then you just can autowire the freemarkerConfig (or use constructor injection):
#Autowired
private Configuration freemarkerConfig;
There is a nice example here, in the attached github code. I was able to use it as a starting point to test my freeMarker code: https://cleantestcode.wordpress.com/2014/06/01/unit-testing-freemarker-templates/

Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException

when i am trying to run the controller Testing in Spring-boot version 1.5.3 Release using the Spring-Boot-Test I am geting the Error Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import com.hanselnpetal.domain.CustomerContact;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
public class ContactsManagementControllerIntegrationTest {
#Autowired
ContactsManagementController contactsManagementController;
#Test
public void testAddContactHappyPath() {
CustomerContact aContact = new CustomerContact();
aContact.setFirstName("Jenny");
aContact.setLastName("Johnson");
// POST our CustomerContact form bean to the controller; check the outcome
String outcome = contactsManagementController.processAddContactSubmit(aContact);
// Assert THAT the outcome is as expected
assertThat(outcome, is(equalTo("success")));
}
}
I am running the class ContactsManagementControllerIntegrationTest.java using (eclipse) the right click on the file and run as junit . any help appreciated.
Ensure that you have below dependency in your pom.xml (maven)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>

JUnit 5 and Spring Framework 4.3.x

Is it right, that JUnit 4.12 and junit-vintage-engine (from JUnit 5) can be used together with Spring Framework 4.3.x?
Is there a possibility to also use junit-jupiter-api and junit-jupiter-engine (both from JUnit 5)?
I assume you mean Spring integration tests, something like:
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(classes = Application.class)
public class ExampleIT {
#Test
public void test() {
}
}
This can be run with the vintage engine.
You can also use JUnit 5 with Spring 4.3 using the prototype for Spring 5. The Jars are available on Jitpack, so in order to convert this test to JUnit 5 just add the Jupiter API and the prototype to your dependencies, e.g. for maven
<dependency>
<groupId>com.github.sbrannen</groupId>
<artifactId>spring-test-junit5</artifactId>
<version>1.0.0.M3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.0.0-M3</version>
<scope>test</scope>
</dependency>
...
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
And instead of the SpringRunner use the SpringExtension and the JUnit jupiter API:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
#ExtendWith(SpringExtension.class)
#SpringBootTest(classes = Application.class)
public class ExampleIT {
#Test
public void test() {
}
}
Hope this helps

Spring Framework: Failed to load ApplicationContext

While running script in Spring framework it is throwing error message as "Failed to load ApplicationContext". I have my ApplicationContext.xml file under src/test/resources
And i was using
#RunWith(value = Parameterized.class)
public class CustomerTest extends FunctionLibrary { ... }
After some suggestions from forum i used
#RunWith(value = Parameterized.class)
#ContextConfiguration(locations = "file:src/test/resources/applicationContext.xml")
public class CustomerTest extends FunctionLibrary { ... }
Still i am getting the same error message. Please anyone tell me how to resolve this issue?
Thanks,
Sudhansu
There are several problems
1) use #RunWith(SpringJUnit4ClassRunner.class)
2) Your path sounds like you have a maven project. In a maven project, src/test/resources will be added to the classpath when the tests run. So use:
#ContextConfiguration(locations = "classpath:applicationContext.xml")
If you haven an other file in src/main/resources withe the same name, then I recommend to rename the one in src/test/resources to test-applicationContext.xml and then use #ContextConfiguration(locations = "classpath:test-applicationContext.xml"), just to reduce the the number of knot in your brain
Complete example:
package com.test.service;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classpath:test-ApplicationContext.xml)
public class WhateverTest {
...
}
pom excerpt:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>

Resources