본문 바로가기
Development/Java

Mockito 클래스의 doThrow()와 thenThrow() 메소드의 차이점과 예제 소스

by 버들도령 2023. 4. 21.
728x90

 

Mockito의 doThrow()와 thenThrow() 메소드는 둘 다 예외를 발생시키기 위한 Mock 객체의 설정 메소드입니다.

  • doThrow() 메소드는 예외를 발생시키는 동작 자체를 설정하는 메소드입니다. 이 메소드는 예외를 발생시키는 Mock 객체 메소드를 실행하기 전에 예외를 발생시킵니다. 이 때, 해당 Mock 객체 메소드는 예외를 발생시키기 때문에 정상적인 반환값은 없습니다. 예를 들어, doThrow() 메소드를 사용하여 예외를 발생시키는 설정을 한 경우, 해당 Mock 객체 메소드를 호출하면 예외가 발생하게 됩니다.
  • 반면에 thenThrow() 메소드Mock 객체 메소드가 호출될 때 예외를 발생시키는 설정을 추가하는 메소드입니다. 이 메소드는 예외를 발생시키는 설정을 한 후에도 Mock 객체 메소드가 예외를 발생시키지 않고 정상적인 값을 반환할 수도 있습니다. 예를 들어, thenThrow() 메소드를 사용하여 예외를 발생시키는 설정을 한 경우, 해당 Mock 객체 메소드를 호출하면 설정한 예외가 발생하게 됩니다.

따라서, doThrow() 메소드는 예외를 발생시키는 동작 자체를 설정하고, thenThrow() 메소드는 Mock 객체 메소드를 호출할 때 예외를 발생시키는 설정을 추가하는 메소드입니다.

두 메소드 사이에는 주요한 차이점이 있는데요.
doThrow() 메서드는 void 메서드에 사용되며
thenThrow() 메서드는 값을 반환하는 메서드에 사용됩니다.

위에서 Mockito의 doThrow()와 thenThrow() 메소드에 대한 주요한 차이점들을 알아보았구요.
이 메소드들을 어떻게 사용하는지를 코드를 통해서 확인해보도록 하겠습니다.

 

Mockito 클래스의 doThrow() / thenThrow() 메소드 사용 예제 코드
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ExampleTest {

    @Test
    void testDoThrow() {
        // mock 생성
        RuntimeException exception = new RuntimeException();
        MyService myService = mock(MyService.class);
        // 예외 던지기
        doThrow(exception).when(myService).doSomething();
        // 예외 처리 검증
        assertThrows(RuntimeException.class, myService::doSomething);
    }

    @Test
    void testThenThrow() {
        // mock 생성
        RuntimeException exception = new RuntimeException();
        MyService myService = mock(MyService.class);
        // 예외 던지기
        when(myService.doSomething()).thenThrow(exception);
        // 예외 처리 검증
        assertThrows(RuntimeException.class, myService::doSomething);
    }

    interface MyService {
        void doSomething();
    }
}

위의 코드에서 
testDoThrow() 메소드는 doThrow() 메소드를 사용하여 예외를 던지고, 
testThenThrow() 메소드는 thenThrow() 메소드를 사용하여 예외를 던지는 예제입니다.
 각각의 테스트는 MyService 인터페이스를 모킹하고, doSomething() 메소드가 호출될 때 미리 지정된 예외를 던집니다. 그 후 assertThrows() 메소드를 사용하여 예외 처리를 검증합니다.


Package org.mockito

Class Mockito

  • doThrow
    public static Stubber doThrow​(Throwable... toBeThrown)
    Use doThrow() when you want to stub the void method with an exception.
    Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

    Example:
       doThrow(new RuntimeException()).when(mock).someVoidMethod();
    Parameters : toBeThrown - to be thrown when the stubbed method is called
  • Returns : stubber - to select a method for stubbing

  • doThrow
    public static Stubber doThrow​(Class<? extends Throwable> toBeThrown)
    Use doThrow() when you want to stub the void method with an exception.
    A new exception instance will be created for each method invocation.
    Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

    Example:
       doThrow(RuntimeException.class).when(mock).someVoidMethod();
    Parameters : toBeThrown - to be thrown when the stubbed method is called
    Returns : stubber - to select a method for stubbingSince:2.1.0

  • doThrow
    public static Stubber doThrow​(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext)
    Same as doThrow(Class) but sets consecutive exception classes to be thrown. Remember to use doThrow() when you want to stub the void method to throw several exceptions that are instances of the specified class.
    A new exception instance will be created for each method invocation.
    Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

    Example:
       doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
    Parameters : toBeThrown - to be thrown when the stubbed method is calledtoBeThrownNext - next to be thrown when the stubbed method is called
    Returns : stubber - to select a method for stubbingSince:2.1.0

Package org.mockito.stubbing

Interface OngoingStubbing<T>

  • thenThrow
    OngoingStubbing<T> thenThrow​(Throwable... throwables)
    Sets Throwable objects to be thrown when the method is called. E.g:
     when(mock.someMethod()).thenThrow(new RuntimeException());
    If throwables contain a checked exception then it has to match one of the checked exceptions of method signature.
    You can specify throwables to be thrown for consecutive calls. In that case the last throwable determines the behavior of further consecutive calls.
    If throwable is null then exception will be thrown.
    See examples in javadoc for Mockito.when(T)

    Parameters : throwables - to be thrown on method invocation
    Returns : object that allows stubbing consecutive call

  • thenThrow
    OngoingStubbing<T> thenThrow​(Class<? extends Throwable> throwableType)
    Sets a Throwable type to be thrown when the method is called. E.g:
     when(mock.someMethod()).thenThrow(RuntimeException.class);

    If the throwable class is a checked exception then it has to match one of the checked exceptions of the stubbed method signature.
    If throwable is null then exception will be thrown.
    See examples in javadoc for Mockito.when(T)
    Note depending on the JVM, stack trace information may not be available in the generated throwable instance. If you require stack trace information, use thenThrow(Throwable...) instead.

    Parameters : throwableType - to be thrown on method invocation
    Returns : object that allows stubbing consecutive callsSince:2.1.0


  • thenThrow
    OngoingStubbing<T> thenThrow​(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown)
    Sets Throwable classes to be thrown when the method is called. E.g:
     when(mock.someMethod()).thenThrow(RuntimeException.class);

    Each throwable class will be instantiated for each method invocation.
    If throwableTypes contain a checked exception then it has to match one of the checked exceptions of method signature.
    You can specify throwableTypes to be thrown for consecutive calls. In that case the last throwable determines the behavior of further consecutive calls.
    If throwable is null then exception will be thrown.
    See examples in javadoc for Mockito.when(T)

    Note since JDK 7, invoking this method will raise a compiler warning "possible heap pollution", this API is safe to use. If you don't want to see this warning it is possible to chain thenThrow(Class)
    Note depending on the JVM, stack trace information may not be available in the generated throwable instance. If you require stack trace information, use thenThrow(Throwable...) instead.

    Parameters :
         toBeThrown - to be thrown on method invocation
         nextToBeThrown - next to be thrown on method invocation

    Returns : object that allows stubbing consecutive calls
    Since:2.1.0

728x90

댓글