Main Tutorials

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 Author

author image
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

Subscribe
Notify of
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
vedyzarc
6 years ago

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.

GillianBC
4 years ago
Reply to  vedyzarc

It worked for me. The DataModelService is autowired in the test case

Catypus
5 years ago

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?

Imran Rajjad
7 years ago

where is the download link?

Pavan
4 years ago

If I put @Test method into other classes it is not getting executed and for assertion I am able to get the bean of that class which containing test methods

Jaga Siva
4 years ago

When a MachineLearningService class has DAO Dependency in it.. what to do? for Unit Testing we should not be using real DB.. instead we should mock them. isn’t it?

smj
4 years ago

How to read a property value for a test class from test resources?
Can I autowire property value in test class?

Catypus
5 years ago

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
5 years ago

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
6 years ago

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 fix this? Please help.

Test comment
6 years ago

Test comment

sahil misri
7 years ago

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

Dinh The Hien
6 years ago

Thank for share. I done for my project