본문 바로가기
spring

[SpringBoot] Test환경에 H2 적용하기

by moonsiri 2021. 8. 4.
728x90
반응형

다음과 같이 db구성이 되어있을때 Test환경에 H2 적용하는 방법입니다.

https://moonsiri.tistory.com/53

 

[Spring] java config로 hikari datasource, transaction aop 설정

pom.xml org.springframework.boot spring-boot-starter-jdbc org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 org.apache.commons commons-dbcp2 mysql mysql-connector-java runtime application.ym..

moonsiri.tistory.com

 

 

우선 pom.xml에 dependency를 추가합니다.

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>test</scope>
		</dependency>

 

 

테스트 환경에서 사용할 h2 구성을 해보겠습니다.

@TestConfiguration
public class H2DbConfig {

	public static final String DATA_SOURCE_NM = "dataSource";
	public static final String TRANSACTION_NM = "txManager";

	private String driverClassName = "org.h2.Driver";
	private String url = "jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1";
	private String username = "sa";
	private String password = "";

	private final String sqlMapperPath = "classpath:/sqlmapper/**/*.xml";

	@Bean(DATA_SOURCE_NM)
	public DataSource dataSource() {
		return DataSourceBuilder.create()
		                        .driverClassName(driverClassName)
		                        .url(url)
		                        .username(username)
		                        .password(password)
		                        .build();
	}

	
    /**
     * sessionfactory
     */
    @Bean(name= "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NM) DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:sqlmapper/*.xml")); //mapper path
        Objects.requireNonNull(sessionFactoryBean.getObject()).getConfiguration().setMapUnderscoreToCamelCase(true); //camelCase
        return sessionFactoryBean.getObject();
    }

    /**
     * sqlsession
     */
    @Bean(name= "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * transaction manager
     */
    @Bean(name= "txManager")
    public PlatformTransactionManager txManager(@Qualifier(DATA_SOURCE_NM) DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        dataSourceTransactionManager.setNestedTransactionAllowed(true); // nested
        return dataSourceTransactionManager;
    }
}

 

위와같이 작성하고 테스트 환경에서 DatabaseConfig.java가 아닌 H2DbConfig.java를 바라보게되면 H2를 사용하게 됩니다.

 

@ExtendWith(SpringExtension.class)
@PropertiesConfigurationForTest
@ContextConfiguration(classes = {
	H2DbConfig.class, UserManage.class, UserManageServiceImpl.class, UserManageDAO.class, RestTemplateConfiguration.class, ObjectMapper.class })
@Sql(scripts = { "classpath:schema.sql", "classpath:data.sql" }, config = @SqlConfig(dataSource = DATA_SOURCE_NM, transactionManager = TRANSACTION_NM))
class UserManageTest extends MockMvcSetting {

	private MockMvc mockMvc;
    
	@Autowired
	private UserManage userManage;

	@Autowired
	UserManageService userManageService;

	@Resource
	private ObjectMapper objectMapper;

	private final String PREFIX = "/user/manage";
	private final String URI_GET_LIST = PREFIX + "/getList";

	public final static List<String> CHECK_URI_PATTERNS = Arrays.asList(
		"/user/manage/*"
	);

	@BeforeEach
	void setUp() {
		final SessionFilter sessionFilter = new SessionFilter(objectMapper);

		mockMvc = MockMvcBuilders.standaloneSetup(userManage)
			.setControllerAdvice(GlobalExceptionHandler.class) // global Exception Handler
			// Filter
			.addFilter(sessionFilter, CHECK_URI_PATTERNS.toArray(new String[]{}))
			.build();
	}

	@Test
	void getUserList() throws Exception {
		// GIVEN
		UserManageDTO.ReqGetList param = new UserManageDTO.ReqGetList();
		param.setPageNo(1);
		param.setPageSize(20);

		// @formatter:off WHEN
		MvcResult mvcResult = mockMvc.perform(
			post(URI_GET_LIST)
				.header(TOKEN_HEADER_NAME, SESSION_TOKEN)
				.content(objectMapper.writeValueAsString(param))
				.contentType(MediaType.APPLICATION_JSON_VALUE))
			.andDo(print())
			.andExpect(status().isOk())
			.andReturn();
		// @formatter:on

		// TEHN
		String content = mvcResult.getResponse().getContentAsString();
		System.out.println("=====================================");
		System.out.println(content);
		System.out.println("=====================================");

		Assertions.assertNotNull(content);
	}
}
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@EnableConfigurationProperties
@PropertySource(value = {
	"classpath:properties/common.properties"
})
public @interface PropertiesConfigurationForTest {
}

 

{root}/test/resources/schema.sql

DROP TABLE IF EXISTS user_manage;

CREATE TABLE user_manage (
    user_id varchar(100) NOT NULL,
    name varchar(100) NOT NULL,
    ...
    reg_ymdt datetime NOT NULL,
    mod_ymdt datetime NOT NULL,
    PRIMARY KEY (user_id),
    KEY IDX_name (name)
) COMMENT='유저 테이블';

 

{root}/test/resources/data.sql

INSERT INTO user_manage (...) VALUES (...);

 

 

728x90
반응형

댓글