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
Please enter at least three characters to search
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • How To Build Web Service Using Spring Boot 2.x

Trending

  • How Trustworthy Is Big Data?
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  1. DZone
  2. Coding
  3. Frameworks
  4. JUnit testing of Spring MVC application: Testing the Service Layer

JUnit testing of Spring MVC application: Testing the Service Layer

By 
Krishna Prasad user avatar
Krishna Prasad
·
Mar. 03, 13 · Interview
Likes (3)
Comment
Save
Tweet
Share
81.3K Views

Join the DZone community and get the full member experience.

Join For Free

In continuation of my earlier blogs on Introduction to Spring MVC and Testing DAO layer in Spring MVC, in this blog I will demonstrate how to test Service layer in Spring MVC. The objective of this demo is 2 fold, to build the Service layer using TDD and increase the code coverage during JUnit testing of Service layer.

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

mvn clean test -Dtest=com.example.bookstore.service.AccountServiceTest

Since in my earlier blog, we have already tested the DAO layer, in this blog we only need to focus on testing service layer. We need to mock the DAO layer so that we can control the behavior in Service layer and cover various scenarios. Mockito is a good framework which is used to mock a method and return known data and assert that in the JUnit.

As a first step we define the AccountServiceTestContextConfiguration class with AccountServiceTest class. If you notice there are 2 beans defined in that class and we marked the as a @Configuration which shows that it is a Spring Context class. In the JUnit test we @Autowired AccountService class. And AccountServiceImpl @Autowired the AccountRepository class. When creating the Bean in the configuration file we also stubbed the AccountRepository class using Mockito,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class AccountServiceTest {

@Configuration
static class AccountServiceTestContextConfiguration {
@Bean
public AccountService accountService() {
return new AccountServiceImpl();
}
@Bean
public AccountRepository accountRepository() {
return Mockito.mock(AccountRepository.class);
}
}

//We Autowired the AccountService bean so that it is injected from the configuration
@Autowired
private AccountService accountService;
@Autowired
private AccountRepository accountRepository;

During the setup of the JUnit we use Mockito mock findByUsername method to return a predefined account object as below

@Before
public void setup() {
Account account = new AccountBuilder() {
{
address("Herve", "4650", "Rue de la gare", "1", null, "Belgium");
credentials("john", "secret");
name("John", "Doe");
}
}.build(true);
Mockito.when(accountRepository.findByUsername("john")).thenReturn(account);
}

Now we write the tests as below and test both the positive and negative scenarios,

@Test(expected = AuthenticationException.class)
public void testLoginFailure() throws AuthenticationException {
accountService.login("john", "fail");
}
@Test()
public void testLoginSuccess() throws AuthenticationException {
Account account = accountService.login("john", "secret");
assertEquals("John", account.getFirstName());
assertEquals("Doe", account.getLastName());
}
}

Finally we verify if the findByUsername method is called only once successfully as below in the teardown,

@After
public void verify() {
Mockito.verify(accountRepository, VerificationModeFactory.times(1)).findByUsername(Mockito.anyString());
// This is allowed here: using container injected mocks
Mockito.reset(accountRepository);
}

AccountService class looks as below,

@Service
@Transactional(readOnly = true)
public class AccountServiceImpl implements AccountService {

@Autowired
private AccountRepository accountRepository;

@Override
public Account login(String username, String password) throws AuthenticationException {
Account account = this.accountRepository.findByUsername(username, password);
} else {
throw new AuthenticationException("Wrong username/password", "invalid.username");
}
return account;
}
}

I hope this blog helped you. In my next blog, I will demo how to build a controller JUnit test.

Reference:

Pro Spring MVC: With Web Flow by by Marten Deinum, Koen Serneels


 

Service layer Spring Framework Web Service JUnit application

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

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: Testing Service Layer Code with JUnit 5 and Mockito, RESTful Web Services
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • How To Build Web Service Using Spring Boot 2.x

Partner Resources

×

Comments
Oops! Something Went Wrong

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
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!