2 * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.testutils.mockito;
10 import static org.junit.jupiter.api.Assertions.assertEquals;
11 import static org.junit.jupiter.api.Assertions.assertNull;
12 import static org.junit.jupiter.api.Assertions.assertThrows;
13 import static org.mockito.ArgumentMatchers.any;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.when;
18 import static org.opendaylight.yangtools.testutils.mockito.MoreAnswers.exception;
21 import org.junit.jupiter.api.Test;
24 * Test to illustrate the basic use of Mockito VS the EXCEPTION_ANSWER. Also useful as example to contrast this approach
25 * with the REAL_OR_EXCEPTION approach illustrated in the MikitoTest.
28 * @author Michael Vorburger
30 class MockitoExampleTutorialTest {
32 interface SomeService {
36 String bar(String arg);
38 // Most methods on real world services have complex input (and output objects), not just int or String
39 int foobar(File file);
43 void usingMockitoWithoutStubbing() {
44 SomeService service = mock(SomeService.class);
45 assertNull(service.bar("hulo"));
49 void usingMockitoToStubSimpleCase() {
50 SomeService service = mock(SomeService.class);
51 when(service.foobar(any())).thenReturn(123);
52 assertEquals(123, service.foobar(new File("hello.txt")));
56 void usingMockitoToStubComplexCase() {
57 SomeService service = mock(SomeService.class);
58 when(service.foobar(any())).thenAnswer(invocation -> {
59 File file = invocation.getArgument(0);
60 return "hello.txt".equals(file.getName()) ? 123 : 0;
62 assertEquals(0, service.foobar(new File("belo.txt")));
66 void usingMockitoExceptionException() {
67 assertThrows(UnstubbedMethodException.class, () -> {
68 SomeService service = mock(SomeService.class, exception());
74 void usingMockitoNoExceptionIfStubbed() {
75 SomeService service = mock(SomeService.class, exception());
76 // NOT when(s.foobar(any())).thenReturn(123) BUT must be like this:
77 doReturn(123).when(service).foobar(any());
78 assertEquals(123, service.foobar(new File("hello.txt")));
79 assertThrows(UnstubbedMethodException.class, service::foo);
83 void usingMockitoToStubComplexCaseAndExceptionIfNotStubbed() {
84 SomeService service = mock(SomeService.class, exception());
85 doAnswer(invocation -> {
86 File file = invocation.getArgument(0);
87 return "hello.txt".equals(file.getName()) ? 123 : 0;
88 }).when(service).foobar(any());
89 assertEquals(123, service.foobar(new File("hello.txt")));
90 assertEquals(0, service.foobar(new File("belo.txt")));