Over a million developers have joined DZone.

Write JUnit Tests in Spring With Mocked and Real Objects

How to use mocked and non-mocked data to write unit tests using the free and open source JUnit framework.

· DevOps Zone

The DevOps zone is brought to you in partnership with Sonatype Nexus. The Nexus suite helps scale your DevOps delivery with continuous component intelligence integrated into development tools, including Eclipse, IntelliJ, Jenkins, Bamboo, SonarQube and more. Schedule a demo today

Microsoft Word - Spring-Junit1.docx

Many times we need to mock the external service or database data to unit test the code. At the same time, we may require to reuse the same unit testing code to test actual external service or database (real objects). How can we make use of the same unit testing code for Mocked and Non-Mocked data?

The document includes the steps to write unit tests using mocked and real data with a simple example, e.g. unit testing implemented with mocked and real data for a repository layer (database layer).

Step 1: Create Spring configuration classes with the profiles “mock “and “dev”. The default profile will be “mock”.

a). Spring configuration with Mocked Bean reference:



publicclass TestConfigurationMock{

@Bean(name = "personRepository")

public PersonRepository getPersonRepository() {

     return MockFactoryBean.getPersonRepository();





b). Spring configuration with real object reference (non-mocked):



publicclass TestConfiguration{

@Bean(name = "personRepository")

public PersonRepository getPersonRepository() {

     return new PersonRepository();





Step 2: Create a MockFactoryBean that gives all mocked beans with sample data:

public class MockFactoryBean {

publicstatic PersonRepository getPersonRepository (){

PersonRepository personRepository = Mockito.mock(PersonRepository.class);

Person person = new Person();


List<Person> personList = new ArrayList<Person>();


return personRepository;




Steps 3: Write JUnit tests with this mocked and real object reference Spring configuration:


@ContextConfiguration(classes = { TestConfigurationMock.class },.class)

@ActiveProfiles(resolver = SpringActiveProfileResolver.class)

publicclass TestPersonRepository {



     private PersonRepository personRepository;



     publicvoid getAllPersonDetails() {

          List<Person> personDetailList = personRepository. getPersonDetails();





From the above JUnit example (TestPersonRepository.java):

  • @ActiveProfiles is used to determine the objects to be injected in the Junit class. If the “mock” profile is enabled, then mocked object will be injected, if the "Dev" profile is enabled, then the actual repository bean will be injected. SpringActiveProfileResolver is included in the project to enable the bean profile based on requirements.
  • JUnit that requires Mock and actual data need to include the following spring configuration classes:
  • @ContextConfiguration(classes = { TestConfigurationMock.class , TestConfiguration.class})

    In the above example, based on the profile, either the Mocked or non-mocked bean will be injected into JUnit at runtime.

    • Mocked configuration can be used in all JUnit tests that require data from an external entity like a database and external services.  Do not add any mocked data in the "Dev" profile and any non-mocked objects in the "mocked" profile.

    • Assert only the key data sets expected in both mocked and non-mocked tests to avoid any JUnit failures upon profile change.
    • Add the duplicate Mocked Bean (with different sample data) in the MockFactoryBean if it is required to cover-up different use cases in the mocked profile.

    The DevOps zone is brought to you in partnership with Sonatype Nexus. Use the Nexus Suite to automate your software supply chain and ensure you're using the highest quality open source components at every step of the development lifecycle. Get Nexus today

    mock objects,spring,junit

    The best of DZone straight to your inbox.

    Please provide a valid email address.

    Thanks for subscribing!

    Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}