개인기록

[오류/해결] spring boot에서 mybatis 테스트하기

ran4 2022. 10. 30. 01:10

 

 

사용 기술

  • java 8, spring boot, mybatis, mysql, maven project
  • junit5 test

 

 

개요

Error creating bean with name 'sqlSessionFactory' defined in class path resource 

[org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]

 

오류가 발생하였다 

 

 

 

원인 (추정)

1. Junit Test에서 DB를 못찾았다

2. application.properties 경로에 이상이 있다

3. spring boot 생성시 만들어지는 Application 클래스에서 DataSourceAutoConfiguration를 exclude로 설정했다

 

 

 

원인을 토대로 해결

 

시도 1

application.properties 경로 변경

에러메세지의 'sqlSessionFactory' 을 보고 경로에 이상이 있다고 생각하여

인텔리제이에서 classpath에 *을 붙여야 경로를 찾는다는 글을 보고 수정하였다

 

classpath:mybatis/mapper/*.xml 에서 아래와 같이 경로를 바꾸었다 

 

 

 

시도 2

처음 테스트할 때 Application 클래스에서

DataSourceAutoConfiguration을 exclude한 것이 생각나서 해당 부분을 없앴다  

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
↓
@SpringBootApplication()

 

 

시도3(해결)

테스트 클래스에서

@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

어노테이션을 추가하였다 

 

테스트 통과!

연결확인용 테스트 코드는 아래에 정리하였다

 

 

 

Mybatis 테스트 코드 정리 

db에 데이터를 1개라도 insert 했다고 가정

아래의 resultType에는 설정한 Dto 혹은 Vo를 넣으면 된다.

 

 

pom.xml 

mybatis와 mybatis test용 dependency 추가 

버전만 사용하고 있는 mybatis의 버전으로 바꾸면 된다 

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>2.2.2</version>
    <scope>test</scope>
</dependency>

 

 

 

Mapper.xml

<mapper namespace="ProductMapper 패키지 경로" >
<!-- 테스트용 조회 -->
<select id="getProductList" resultType="ProductDto">
	select * from coffee_product where productId = #{productId}
</select>
</mapper>

 

 

Dto

@Getter //lombok
@Setter
public class ProductDto {

  private Integer productId; //상품 ID pk
  private String pName; //상품명
  private int p_price; //가격
 
 }

 

 

Mapper

@Mapper
public interface ProductMapper {
 //상품 조회
 ProductDto getProductList(Integer productId);

}

 

 

Test

// JUnit5 사용 시 작성, MybatisTest 2.0.1버전 이상에서 생략 가능
// @ExtendWith(SpringExtension.class)
// JUnit4 사용 시 작성
// @RunWith(SpringRunner.class)

@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ProductTest {

    @Autowired
    private ProductMapper mapper;

    @Test
    @DisplayName("select test")
    public void selectTest() throws Exception {
        //given
        Integer productId = 1;

        //when
        ProductDto dto = mapper.getProductList(productId);

        //then
        Assertions.assertThat(dto.getProductId()).isEqualTo(1);
        System.out.println("상품 조회 데이터 " + dto);
    }
}

 

 

 

 

 

참고 블로그 : https://plz-exception.tistory.com/28