티스토리 뷰

Develop/Java

[JUnit5] Service Mock Test

AussieKorean 2023. 5. 7. 02:24
728x90

** 영어 공부중이라 가급적 영어로 작성합니다. 아직 영어가 많이 부족해서 틀린 표현이 많을 수 있습니다. 알려주시면 감사하겠습니다.(I try to write in English as much as I can because I'm studying English as well. There might be wrong English Expression. I appreciate if you let me know correct English. Thank you.)

# Condition
- Prefer to use Mockito NOT BDD Mockito Pattern.(가급적 BDD Mockito 패턴이 아닌 Mockito 사용)
- Unit Test with Mock. (withouth Spring full environment.) (Mock 환경 단위 테스트. (Spring full 환경 로드 하지 않음)
  Use a mock mapper instead of real mapper because of Unit Test.
 
# Source Code
@DisplayName("SampleService 테스트")
@Slf4j
@ExtendWith(MockitoExtension.class)
class SampleServiceTest {
    @InjectMocks  // Inject mocks into this service class not to use real mapper class.
    SampleService sampleService;
    @Mock
    SampleMapper sampleMapper;

    @SuppressWarnings("unchecked")
    @DisplayName("@Service :샘플 데이터 리스트 가져오기")
    @Test
    final void testSelectSampleDataList() {
        log.debug("@testSelectSampleDataList");
        //given
        //Make dummy data as stub (Stub용 더미 데이터 생성)
        List<Map<String, Object>> listStubData = (List<Map<String, Object>>) SampleUtil.getDummyDataList(3, null);
        Map<string, object> mapParam = new HashMap<>();  // parameter for mapper's method.(Mapper용 파라메터)
        //Set return when a specific method called.(특정 메소드가 호출될 때의 리턴값 설정)
        when((List<Map<String, Object>>) sampleMapper.selectSampleDataList(mapParam)).thenReturn((List<Map<String, Object>>) listStubData);

        //when
        //Call the service tested : the return value will be returned set with "when" method above (테스트할 서비스 호출 :위의 when으로 설정한 리턴값이 리턴 됨)
        List<Map<String, Object>> listResult = (List<Map<String, Object>>) sampleService.selectSampleDataList(mapParam);
        log.debug("listResult:{}", listResult.toString());

        //then
        //verify the expect values.
        assertThat(listResult.size()).isEqualTo(iExpect);
    }
}

728x90

'Develop > Java' 카테고리의 다른 글

[Code Formatter] Google Code Style For Eclipse & IntelliJ.  (0) 2023.08.11
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함