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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Spring Boot - Unit Test your project architecture with ArchUnit
  • Top 10 Advanced Java and Spring Boot Courses for Full-Stack Java Developers
  • Advanced Functional Testing in Spring Boot Using Docker in Tests

Trending

  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Driving DevOps With Smart, Scalable Testing
  1. DZone
  2. Coding
  3. Frameworks
  4. Unit Testing in Spring Boot: DAO, Service, and Controller With the JDBC

Unit Testing in Spring Boot: DAO, Service, and Controller With the JDBC

Need help with unit testing?

By 
James Jian user avatar
James Jian
·
Apr. 02, 19 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
63.2K Views

Join the DZone community and get the full member experience.

Join For Free

In this unit testing example with Spring Boot, I am going to useLabstatOutputReportDao, LabstatService, andLabstatController.

For DAO:

@Transactional means rollback on the transaction after testing. Additionally, @SpringBootTest means that we are running unit testing with the Spring Boot feature.

Note: for DAO, we directly connect to DB for testing.

@RunWith(SpringRunner.class)
@Transactional
@SpringBootTest
public class LabstatOutputReportDaoTest {

private static final Logger log = LoggerFactory.getLogger(LabstatOutputReportDaoTest.class);

@Autowired
ILabstatOutputReportDao labOutputDao;

@Test
public void getAllLabOutputTest() {

log.info("LabstatOutputReportDaoTest::getAllLabOutputTest()");

if(labOutputDao.getAllLabOutput().isPresent()) {
List<Map<String, Object>> actualList = labOutputDao.getAllLabOutput().get();
assertThat(actualList).isNotNull();
}
}
}


For service, we are using Mokito for mocking beans. We use @MockBean for mocking the DAO. And then, we use @TestConfiguration to provide a mock bean for the service.

@RunWith(SpringRunner.class)
public class LabstatServiceTest {
  private static final Logger log = LoggerFactory.getLogger(LabstatServiceTest.class);

  @TestConfiguration
static class LAUSUtilityServiceTestConfiguration{

@Bean
public LabstatService labstatService() {
return new LabstatService();
}
}

  @MockBean
private ILabstatOutputReportDao labstatOutputReportDao;

  @Autowired
private LabstatService labstatSrvc;

  @Before
public void setUp() throws SQLException {

      Mockito.when(labstatOutputReportDao.getAllLabOutput()).thenReturn(getAllLabOutputMockReturn());

    }

  @Test
public void getAllLabOutputTest() {

log.info("unit test getAllLabOutputTest()...");

int actSize = labstatSrvc.getAllLabOutput().size();

int expSize = 2;

assertThat(actSize).isEqualTo(expSize);

}

  private Optional<List<Map<String, Object>>> getAllLabOutputMockReturn(){

List<Map<String, Object>> list = new ArrayList<>();
list = IntStream.range(1, 3).mapToObj((idx) ->{
Map<String, Object> map = new HashMap<>();
map.put(String.valueOf(idx), "TASKNUM"+idx*10);

return map;

}).collect(Collectors.toList());

return Optional.ofNullable(list);



}


For the controller, we will be using @wemvctest for controller testing. Additionally, we will be using jsonPath for testing return if return as:

@RunWith(SpringRunner.class)
@WebMvcTest(value = LabstatController.class, secure = false)
public class LabstatControllerTest {
private static final Logger log = LoggerFactory.getLogger(LabstatControllerTest.class);

  @Autowired
private MockMvc labMVc;

@MockBean
private LabstatService labstatSrvc;

    @Before
public void setup() {
Mockito.when(labstatSrvc.getAllStates()).thenReturn(getAllStatesServiceMockReturn());
}


  @Test
public void testLabCtrlGetStates() throws Exception {
// add more testing realted to json return in controller later on

log.info("unit testing controller testLabCtrlGetStates()...");

labMVc.perform(MockMvcRequestBuilders.get("/rest/v1/public/getSPData").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
// test the first data in states should be st1
.andExpect(jsonPath("$.states.states[0].name", is("st1")));
}

  private Map<String, Object> getAllStatesServiceMockReturn() {
Map<String, Object> stateMap = new HashMap<>();
List<State> stateList = new ArrayList<>();

for (int i = 1; i < 10; i++) {
State tmpST = new State();
tmpST.setAreaseq(i);
tmpST.setBlsRegion(i);
tmpST.setName("st" + i);
tmpST.setStateCode(String.valueOf(10 + i));
tmpST.setStateNum(String.valueOf(100 + i));
stateList.add(tmpST);

}
stateMap.put("states", stateList);

return stateMap;
}
}


Happy testing!

Spring Framework Decentralized autonomous organization unit test Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • Spring Boot - Unit Test your project architecture with ArchUnit
  • Top 10 Advanced Java and Spring Boot Courses for Full-Stack Java Developers
  • Advanced Functional Testing in Spring Boot Using Docker in Tests

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!