Programming-[Backend]/Java

[경험 요약] 자바 테스트 객체 자동으로 만들기: Instancio 라이브러리

컴퓨터 탐험가 찰리 2024. 5. 20. 08:48
728x90
반응형

 

 

오랜만에 자바-스프링 프로젝트를 진행하면서 테스트 케이스상 필요한 given 객체들을 만들어내야하는데, 각 속성값들을 직접 다 지정해줘야하는게 너무 불편했다. 파이썬-장고 계열에서는 Model Bakery를 사용했었는데, 자바에서는 그런 라이브러리를 사용한 기억이 없어서 라이브러리를 찾아보기로 했다!

 

Instancio

https://mvnrepository.com/artifact/org.instancio/instancio-junit

 

 

instancio를 maven repository에서 import 해와서 build.gradle에 포함시켰다.

 

간단한 사용법은 예시는 아래와 같다. user-guide를 5~10분만 보면 바로 어떤 건지 알 수 있다.

https://www.instancio.org/user-guide/

 

User Guide - Instancio

 

www.instancio.org

 

 

given 조건 예시

//상품에 관련한 객체들을 만들어본다.
// given
GoodsDto requestGoods = Instancio.of(GoodsDto.class).create();
List<GoodsEntity> goodsInDB =
//List로 만들고 싶을땐 .ofList() 메서드를 사용한다.
    Instancio.ofList(GoodsEntity.class)
        .size(5)
        //set, field 메서드를 사용한다. 만들고자하는 객체에 getter가 반드시 있어야한다.
        .set(field(GoodsEntity::getCode), requestGoods.getCode())
        .set(field(GoodsEntity::getName), requestGoods.getName())
        .set(field(GoodsEntity::getPrice), requestGoods.getPrice())
        .create();

// 객체를 1개만 만들고 싶고, 따로 field들을 지정하지 않아도 타입에 맞게 자동으로 지정하고 싶으면 .of() 메서드를 사용한다.
GoodsDto requestGoodsDto = Instancio.of(GoodsDto.class).create();

 

728x90
반응형