JUnit + Spring integration example

In this tutorial, we will show you how to test the Spring DI components with JUnit frameworks.

Technologies used :

  1. JUnit 4.12
  2. Hamcrest 1.3
  3. Spring 4.3.0.RELEASE
  4. Maven

1. Project Dependencies

To integrate Spring with JUnit, you need spring-test.jar

pom.xml

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.0.RELEASE</version>
            <scope>test</scope>
        </dependency>

2. Spring Components

A simple Spring components, later for testing.

2.1 An interface.

DataModelService.java

package com.mkyong.examples.spring;

public interface DataModelService {

    boolean isValid(String input);

}

2.2 Implementation of above interface.

MachineLearningService.java

package com.mkyong.examples.spring;

import org.springframework.stereotype.Service;

@Service("ml")
public class MachineLearningService implements DataModelService {

    @Override
    public boolean isValid(String input) {
        return true;
    }

}

2.2 A Spring configuration file, component scanning.

AppConfig.java

package com.mkyong.examples.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"com.mkyong.examples.spring"})
public class AppConfig {
}

3. JUnit + Spring Integration Examples

Annotate the JUnit test class with @RunWith(SpringJUnit4ClassRunner.class) and loads the Spring configuration file manually. Refer below :

MachineLearningTest.java

package com.mkyong.spring;

import com.mkyong.examples.spring.AppConfig;
import com.mkyong.examples.spring.DataModelService;
import com.mkyong.examples.spring.MachineLearningService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class MachineLearningTest {

	//DI
    @Autowired
    @Qualifier("ml")
    DataModelService ml;

    @Test
    public void test_ml_always_return_true() {

        //assert correct type/impl
        assertThat(ml, instanceOf(MachineLearningService.class));

        //assert true
        assertThat(ml.isValid(""), is(true));

    }
}

Done.

4. FAQs

4.1 For XML, try this :


import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(locations = {
        "classpath:pathTo/appConfig.xml",
        "classpath:pathTo/appConfig2.xml"})
public class MachineLearningTest {
//...
}

4.2 For multiple configuration files :


import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(classes = {AppConfig.class, AppConfig2.class})
public class MachineLearningTest {
//...
}

References

  1. Spring IO – Unit Testing
  2. Spring IO – Integration Testing
  3. TestNG + Spring Integration Example
  4. Spring Batch unit test example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
9 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
CatypusVishal PatelDinh The HienKhanhTest comment Recent comment authors
newest oldest most voted
vedyzarc
Guest
vedyzarc

Hello! It looks like you forgot to mention how to run tests? When I run my tests redesigned to “Spring-based” in IDEA 15 it seems to me that SpringContext is not loaded, because beans are not autowired.

Imran Rajjad
Guest
Imran Rajjad

where is the download link?

Catypus
Guest
Catypus

This is super weird!
error reading /Users/usr/.m2/repository/org/springframework/spring-core/4.3.0.RELEASE/spring-core-4.3.0.RELEASE.jar; zip file is empty

Any ideas?

Catypus
Guest
Catypus

Hi, for Java 11, Test is red:

import org.junit.Test;

So I changed it Junit413 to Compile instead of Test and now the import works. How can I get it to both Test and Compile?
Same issue with these:
Hamcrest imports, SpringJUnit4ClassRunner, ContextConfiguration

Oh right… I have to put the Test in the Test directory LOL!

Vishal Patel
Guest
Vishal Patel

Above setup works fine with maven-test.
But it fails if I wanted to Run Individual Test class or Test method.
MachineLearningTest class can not run individually.
Can you suggest a solution which works for both maven and individual test both.
Thanks in advance.

Khanh
Guest
Khanh

Hello there! This is great tutorial. But, can you help? For example, I have class A like this: @Component public class A{ } And class B have dependency with A like: @Component public class B{ @Autowired private A a; public void method() { // do something with a } } This is working fine that a is instantiated by @Autowired. But how about in the Test class of B, like: public class BTest { @Autowired private B b; // This is null, means it did not instantiate b instance of class B. } So what I have to do to… Read more »

Dinh The Hien
Guest
Dinh The Hien

Thank for share. I done for my project

Test comment
Guest
Test comment

Test comment

sahil misri
Guest
sahil misri

Does this work with Java 6. I am getting an error major.minor 51