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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Data Engineering
  3. Databases
  4. JUnit testing of Spring MVC application: Testing DAO layer

JUnit testing of Spring MVC application: Testing DAO layer

Krishna Prasad user avatar by
Krishna Prasad
·
Mar. 01, 13 · Interview
Like (0)
Save
Tweet
Share
78.97K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top Authentication Trends to Watch Out for in 2023
  • Core Machine Learning Metrics
  • Deploying Java Serverless Functions as AWS Lambda
  • Writing a Modern HTTP(S) Tunnel in Rust

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: