[java testcode]

정독 https://dingdingmin-back-end-developer.tistory.com/entry/Springboot-Test-%EC%BD%94%EB%93%9C-%EC%9E%91%EC%84%B1-1

 

Springboot Test 코드 작성

Test 코드를 작성하는 법을 알아보기 전에 Test 코드의 필요성에 대해서 알아보겠습니다. 1. 왜 Test 코드를 작성하는가? 크게 2가지 이유가 있습니다.' 1-1. Test 코드를 작성하지 않고 결과를 검증하

dingdingmin-back-end-developer.tistory.com

https://sjh9708.tistory.com/195

 

[Spring Boot] 테스트 코드 : 시작하기 (JUnit)

테스트 코드의 필요성 및 실천 방법론 테스트 코드의 필요성과 "좋은 테스트 코드"를 작성하기 위한 방법론에 대해서 작성한 내용이다. 테스트 코드를 "왜" 작성하고 "어떠한 마음가짐"으로 임

sjh9708.tistory.com

https://greedy0110.tistory.com/57

 


ctrl shift t

 

when

when 함수를 사용하면 Mock 객체의 행동을 설정할 수 있다. [어떤 동작을 할 때~]

[어떤 것을 한다] thenReturn, thenThrow, thenAnswer

when(repository.findById()).thenReturn("hi");
when(repository.getNews()).thenThrow(new Exception()); // 해당 함수 호출 시 예외가 발생하도록 한다

try {
	repository.getNews()
} catch (Exception e) {
	sysout("에러발생")
}

// interface NewsRepository 
@Throws(Exception) // throw 어노테이션으로 에러 지정해줘야 함
getNews

do

 FixCarStatusResponse response = doNothing().when(repository).updateCarStatus(carIdArray[0], request.getStatus());
doThrow(new Exception("Invalid car status")).when(controller).fixCarStatus(request);

 

assert

Assertions.assertThat(실제값).isEqualTo(기댓값);

Assertions.assertThat(실제값).isNotEqualTo(기댓값);

Assertions. assertThat(실제객체).isInstanceOf(객체 예상 타입);

Assertions. assertThat(실제값).isNull();

 

▼ assertThrows(SomeException.class, () -> code) : 해당 코드에서 임의의 SomeException이 발생 시 테스트를 통과하게 된다.

assertThrows(NoSuchElementFoundException.class, () -> {
        Long insertTagId = tagService.addTag(request, Long.MAX_VALUE);
});
Exception exception = assertThrows(Exception.class, () -> controller.fixCarStatus(request));

  getTags()로 불러 온 Tag List를 extracting() 메서드를 통해서 특정 필드를 추출한 후, 해당 필드의 리스트에 비교 대상들이 포함되었는지를 contains()를 통해 검증한다.

assertThat(result.getTags())
        .extracting(e -> e.getTagId())
        .contains(tag1Id, tag2Id);

 

.orElseThrow(()-> new Exception("");

assertThatThrownBy( () -> 예외를 발생시킬 로직).isInstanceOf(예외 클래스);

ㄴ 예외발생검증 메서드. ::: 예외가 발생한다면 테스트를 통과, 예외발생X라면 테스트 실패

ㄴ assertThatThrownBy(() -> memberService.createMember("hi1",10)).isInstanceOf(IllegalStateException.class);

 

  Mockito.when(가짜 객체의 로직 실행). thenReturn(실행되면 이것을 반환한다.)

Mockito.when(memberRepository.findByName("hi1")).thenReturn(Optional.of(member1));

 

verify함수

인자로 mock 객체를 받는다. 해당 mock 객체에 원하는 상호작용이 있었는지 검증한다. (메서드 호출 여부, 필드 참조 여부)

verify(repository, times(1)).getNews() // 한번 호출됐는가

verify(repository, never()).getNews() // 호출 안됐는가

atLeat

atMost

only

 

JPA의 Test

@DataJpaTest : @Transaction이 포함돼 1개의 테스트가 끝나면 롤백