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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Hints for Unit Testing With AssertJ

Trending

  • Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines
  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern
  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • When a Coding Agent Fixes the Test Instead of the Bug

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Using JUnit Theories with Spring and Mockito

Using JUnit Theories with Spring and Mockito

By 
Lucas Godoy
·
Dec. 11, 12 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
17.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

What is a Theory?

Functionally, a theory is an alternative to JUnit's parameterized tests. Semantically, a theory encapsulates the tester's understanding of an object's universal behavior. That is, whatever it is that a theory asserts, it is expected to be true for all data. Theories should be especially useful for finding bugs in edge cases.

Contrast this with a typical unit test, which asserts that a specific data point will have a specific outcome, and only asserts that. (For this reason, typical unit tests are sometimes called example-based tests to contrast them with theories.)

This is very nice in theory, but...

A @Theory needs a special JUnit runner (Theories.class). So if you want to use Spring and/or Mockito together with theories, you have a problem. All of these features need a different runner and you can only use one on each test class.

The solution

For Mockito is easy. Instead of using the @Mock annotiation, you can use the static createMock method. One problem solved.

For Spring is a little bit trickier. First of all, you have to use @ContextConfiguration to declare the XML with the bean definitions that you need. But the trickiest part is that you have to tell Spring how to do the autowiring without using its own runner. This can be accomplish adding this line to the @Before method:

new TestContextManager(getClass()).prepareTestInstance(this);

Basic Usage Example

package org.mackenzine.theories;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

import java.util.Date;

import org.junit.Before;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;

@RunWith(Theories.class)
@ContextConfiguration("classpath:parser.xml")
public class QuoteTheoriesTest {

   private static String deleteMessage = "deleteMessage";
   private static String updateMessage = "updateMessage";

   private QuoteFactory factory;

   private final Event event = Mockito.mock(Event.class);
   private final Contract contract = Mockito.mock(Contract.class);
   private final Commodity commodity = Mockito.mock(Commodity.class);

   @Autowired
   private Parser parser;

   @Before
   public void setUp() throws Exception {
     factory = new QuoteFactory();
     new TestContextManager(getClass()).prepareTestInstance(this);
   }

   @DataPoints
   public static String[] getEventTypes() {
     return new String[] { updateMessage, deleteMessage };
   }

   @Theory
   public void shouldCreateQuote(final String message) throws Exception {
     Date now = new Date();

     when(event.getParsedMessage()).thenReturn(parser.parse(message));
     when(event.getContract()).thenReturn(contract);
     when(event.getTradeDate()).thenReturn(now);
     when(contract.getExternalCode()).thenReturn("externalCode");
     when(contract.getCommodity()).thenReturn(commodity);
     when(commodity.getCommodityCode()).thenReturn("code");

     Quote quote = factory.createQuote(event);

     assertNotNull(quote);

     assertEquals("code", quote.getCommodityCode());
     assertEquals(now, quote.getTradeDate());
   }
}
Sources

Definition of Theories:
https://blogs.oracle.com/jacobc/entry/junit_theories

Original Idea for Parameterized Tests:
http://stackoverflow.com/questions/8974977/spring-parameterized-theories-junit-tests

Thread on SpringSource:
http://forum.springsource.org/showthread.php?78929-Is-Theory-supported

Open Issue in SpringSource for Parameterized Tests (not for Theories):
https://jira.springsource.org/browse/SPR-5292

Spring Framework JUnit Mockito unit test

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Hints for Unit Testing With AssertJ

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook