Back to Repositories

Testing MyBatis Annotation-based User Mapping in spring-boot-examples

This test suite validates the UserMapper functionality in a Spring Boot application using MyBatis annotations. It covers essential CRUD operations for user management, ensuring reliable data persistence and retrieval through MyBatis-annotated mappings.

Test Coverage Overview

The test suite provides comprehensive coverage of UserMapper operations:
  • Insert operations with multiple user records
  • Query functionality for retrieving user lists
  • Update operations with user attribute modifications
  • Data integrity validation through assertions

Implementation Analysis

The testing approach utilizes Spring Boot’s testing framework with JUnit integration. It implements @SpringBootTest for full application context loading and dependency injection of the UserMapper component. The tests follow a clear arrange-act-assert pattern with explicit verification of expected outcomes.

Technical Details

Key technical components include:
  • SpringRunner for test execution
  • JUnit 4 testing framework
  • MyBatis annotation-based mapping
  • Spring Boot test context configuration
  • Automated dependency injection with @Autowired
  • UserSexEnum for enumerated type handling

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Isolated test methods for specific functionality
  • Clear test method naming conventions
  • Proper assertion usage for validation
  • Spring Boot test configuration best practices
  • Effective use of Spring’s dependency injection

ityouknow/spring-boot-examples

2.x/spring-boot-mybatis/spring-boot-mybatis-annotation/src/test/java/com/neo/mapper/UserMapperTest.java

            
package com.neo.mapper;

import java.util.List;

import com.neo.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.neo.enums.UserSexEnum;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

	@Autowired
	private UserMapper userMapper;

	@Test
	public void testInsert() throws Exception {
		userMapper.insert(new User("aa1", "a123456", UserSexEnum.MAN));
		userMapper.insert(new User("bb1", "b123456", UserSexEnum.WOMAN));
		userMapper.insert(new User("cc1", "b123456", UserSexEnum.WOMAN));

		Assert.assertEquals(3, userMapper.getAll().size());
	}

	@Test
	public void testQuery() throws Exception {
		List<User> users = userMapper.getAll();
		System.out.println(users.toString());
	}
	
	
	@Test
	public void testUpdate() throws Exception {
		User user = userMapper.getOne(30l);
		System.out.println(user.toString());
		user.setNickName("neo");
		userMapper.update(user);
		Assert.assertTrue(("neo".equals(userMapper.getOne(30l).getNickName())));
	}

}