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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

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

  • Driving Streaming Intelligence On-Premises: Real-Time ML With Apache Kafka and Flink
  • A Decade of Transformation: The Evolution of Web Development
  • How Docker Desktop Enhances Developer Workflows and Observability
  • Beyond Automation: How Artificial Intelligence Is Transforming Software Development
  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.1K 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.

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.

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: