package com.kkjavatutorials;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
/**
* Method Exception Throwing testing using Mockito
* @author KK JavaTutorials
*/
public class WordDictionaryTest {
/**
* Test for non-void Return Type method with Exception
*/
@Test
public void nonVoidMethodThrowingExceptionMockitoTest() {
try {
WordDictionary wordDictionary = mock(WordDictionary.class);
when(wordDictionary.getMeaning(anyString()))
.thenThrow(NullPointerException.class);
wordDictionary.getMeaning("awesome");
} catch (Exception e) {
System.out.println("Exception occured!!");
assertTrue(e instanceof NullPointerException);
}
}
/**
* Test for void Return Type method with Exception
*/
@Test
public void voidMethodThrowingExceptionMockitoTest() {
WordDictionary wordDictionary = mock(WordDictionary.class);
doThrow(new IllegalStateException("Error occurred!!"))
.when(wordDictionary)
.add(anyString(), anyString());
assertThrows(IllegalStateException.class, ()->wordDictionary.add("awesome", "Very Good"));
}
/**
* Configuring Spy to throw an exception the same way we've done with the mock
*/
@Test
public void nonVoidMethodThrowingExceptionWithSpyMockitoTest() {
String emptyWord ="";
try {
WordDictionary wordDictionary = new WordDictionary();
WordDictionary spyWordDictionary = spy(wordDictionary);
when(spyWordDictionary.getMeaning(emptyWord))
.thenThrow(new IllegalArgumentException("Input is not valid!!"));
spyWordDictionary.getMeaning(emptyWord);
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
assertEquals("Input is not valid!!",e.getMessage());
}
}
}