DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • JSON-Based Serialized LOB Pattern
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Troubleshooting Memory Leaks With Heap Profilers
  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects

Trending

  • Beyond the Glass Slab: How AI Voice Assistants are Morphing Into Our Real-Life JARVIS
  • Jakarta EE 11 and the Road Ahead With Jakarta EE 12
  • A Keycloak Example: Building My First MCP Server Tools With Quarkus
  • My Dive into Local LLMs, Part 2: Taming Personal Finance with Homegrown AI (and Why Privacy Matters)
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Write JUnit Tests in Spring With Mocked and Real Objects

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.

By 
Saravanan Kandasamy user avatar
Saravanan Kandasamy
·
Feb. 16, 16 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
16.9K Views

Join the DZone community and get the full member experience.

Join For Free
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:

@Configuration

@Profile("mock")

publicclass TestConfigurationMock{



@Bean(name = "personRepository")

public PersonRepository getPersonRepository() {

     return MockFactoryBean.getPersonRepository();

}

…

.   

}

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

@Configuration

@Profile("dev")

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();

Person.setName(“ABC”);



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

when(personRepository.getPersonDetails()).thenReturn(personList);



return personRepository;

}

..

}

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

@RunWith(SpringJUnit4ClassRunner.class)

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

@ActiveProfiles(resolver = SpringActiveProfileResolver.class)

publicclass TestPersonRepository {

    

     @Autowired

     private PersonRepository personRepository;

    

     @Test

     publicvoid getAllPersonDetails() {

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

          Assert.assertNotNull(personDetailList.get(0).getPersonName());

     }



..



}

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.
    unit test Spring Framework JUnit Object (computer science) Database Data (computing) Profile (engineering)

    Opinions expressed by DZone contributors are their own.

    Related

    • JSON-Based Serialized LOB Pattern
    • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
    • Troubleshooting Memory Leaks With Heap Profilers
    • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects

    Partner Resources

    ×

    Comments

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • [email protected]

    Let's be friends: