Back to Repositories

Testing UserMapper CRUD Operations in spring-boot-examples

This test suite validates the UserMapper functionality in a Spring Boot application using MyBatis XML configuration. It covers essential CRUD operations for user management, ensuring proper database interactions and data persistence.

Test Coverage Overview

The test suite provides comprehensive coverage of UserMapper operations including:
  • User insertion with validation of count
  • User query operations with null checking
  • User update functionality with assertion verification
Key integration points include Spring Boot context loading and MyBatis mapper interactions.

Implementation Analysis

The testing approach utilizes Spring Boot’s test framework with JUnit 4 integration. It demonstrates proper dependency injection using @Autowired for UserMapper, and leverages SpringRunner for test execution. The implementation follows a clear pattern of arrange-act-assert testing methodology.

Technical Details

Testing tools and configuration include:
  • JUnit 4 testing framework
  • Spring Boot Test context
  • SpringRunner test runner
  • MyBatis mapper integration
  • Custom UserEntity and UserSexEnum implementations

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Proper test isolation and setup
  • Clear test method naming conventions
  • Effective use of assertions
  • Comprehensive CRUD operation coverage
  • Proper exception handling with throws Exception

ityouknow/spring-boot-examples

1.x/spring-boot-mybatis-xml/src/test/java/com/neo/mapper/UserMapperTest.java

            
package com.neo.mapper;

import java.util.List;

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.entity.UserEntity;
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 UserEntity("aa", "a123456", UserSexEnum.MAN));
		UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));
		UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));

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

	@Test
	public void testQuery() throws Exception {
		List<UserEntity> users = UserMapper.getAll();
		if(users==null || users.size()==0){
			System.out.println("is null");
		}else{
			System.out.println(users.toString());
		}
	}
	
	
	@Test
	public void testUpdate() throws Exception {
		UserEntity user = UserMapper.getOne(6l);
		System.out.println(user.toString());
		user.setNickName("neo");
		UserMapper.update(user);
		Assert.assertTrue(("neo".equals(UserMapper.getOne(6l).getNickName())));
	}

}