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

Related

  • Application Mapping: 5 Key Benefits for Software Projects
  • Externalize Microservice Configuration With Spring Cloud Config
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • How To Build Web Service Using Spring Boot 2.x

Trending

  • AI Paradigm Shift: Analytics Without SQL
  • Dear Micromanager: Your Distrust Has a Job; It’s Just Not the One You’re Doing
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. JUnit testing of Spring MVC application: Testing DAO layer

JUnit testing of Spring MVC application: Testing DAO layer

By 
Krishna Prasad user avatar
Krishna Prasad
·
Mar. 01, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
80.2K Views

Join the DZone community and get the full member experience.

Join For Free

In continuation of my blog JUnit testing of Spring MVC application – Introduction, in this blog, I will show how to design and implement DAO layer for the Bookstore Spring MVC web application using Test Driven development.

For people in hurry, get the latest code from Github and run the below command

mvn clean test -Dtest=com.example.bookstore.repository.JpaBookRepositoryTest

As a part of TDD,

  • Write a basic CRUD (create, read, update, delete) operations on a Book DAO class com.example.bookstore.repository.JpaBookRepository. Don’t have the database wiring yet in this DAO class. Once we build the JUnit tests, we use JPA as a persistence layer. We also use H2 as a inmemory database for testing purpose.
  • Create Book POJO class

Create the JUnit test as below,

public class JpaBookRepositoryTest {
@Test
public void testFindById() {
Book book = bookRepository.findById(this.book.getId());
assertEquals(this.book.getAuthor(), book.getAuthor());
assertEquals(this.book.getDescription(), book.getDescription());
assertEquals(this.book.getIsbn(), book.getIsbn());
}

@Test
public void testFindByCategory() {
List<Book> books = bookRepository.findByCategory(category);
assertEquals(1, books.size());

for (Book book : books) {
assertEquals(this.book.getCategory().getId(), category.getId());
assertEquals(this.book.getAuthor(), book.getAuthor());
assertEquals(this.book.getDescription(), book.getDescription());
assertEquals(this.book.getIsbn(), book.getIsbn());
}
}

@Test
@Rollback(true)
public void testStoreBook() {
Book book = new BookBuilder() {
{
description("Something");
author("JohnDoe");
title("John Doe's life");
isbn("1234567890123");
category(category);
}
}.build();

bookRepository.storeBook(book);

Book book1 = bookRepository.findById(book.getId());

assertEquals(book1.getAuthor(), book.getAuthor());
assertEquals(book1.getDescription(), book.getDescription());
assertEquals(book1.getIsbn(), book.getIsbn());
}
}

If you notice since the JpaBookRepository is only a skeleton class without implementation, all the tests will fail.

As a next step, we need to create a Configuration and wire a datasource, and for the test purpose we will be using H2 database. And we also need to wire this back to JUnit test as below,

@Configuration
public class InfrastructureContextConfiguration {
@Autowired
private DataSource dataSource;
//some more configurations..
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
builder.setType(EmbeddedDatabaseType.H2);
return builder.build();
}
}

//JUnit test wiring is as below

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { InfrastructureContextConfiguration.class, TestDataContextConfiguration.class })
@Transactional
public class JpaBookRepositoryTest {
//the test methods
}

Next step is to setup and teardown sample data in the JUnit test case as below,

public class JpaBookRepositoryTest {
@PersistenceContext
private EntityManager entityManager;

private Book book;
private Category category;

@Before
public void setupData() {
EntityBuilderManager.setEntityManager(entityManager);

category = new CategoryBuilder() {
{
name("Evolution");
}
}.build();

book = new BookBuilder() {
{
description("Richard Dawkins' brilliant reformulation of the theory of natural selection");
author("Richard Dawkins");
title("The Selfish Gene: 30th Anniversary Edition");
isbn("9780199291151");
category(category);
}
}.build();
}

@After
public void tearDown() {
EntityBuilderManager.clearEntityManager();
}
}

Once we do the wiring, we need to implement the com.example.bookstore.repository.JpaBookRepository and use JPA to do the CRUD on the database and run the tests. The tests will succeed.

Finally if you run Cobertura for this example from STS, we will get over 90% of line coverage for com.example.bookstore.repository.JpaBookRepository. In case you want to try few exercises you can implement repository for Account and User.

I hope this blog helped you. In my next blog I will talk about Mochito and Implementing the Service layer.


Decentralized autonomous organization JUnit application Spring Framework Database Testing

Published at DZone with permission of Krishna Prasad. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Application Mapping: 5 Key Benefits for Software Projects
  • Externalize Microservice Configuration With Spring Cloud Config
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • How To Build Web Service Using Spring Boot 2.x

Partner Resources

×

Comments

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

  • 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