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.tests;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNull;
12 import static org.junit.Assert.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.Test;
22 import org.opendaylight.yangtools.testutils.mockito.UnstubbedMethodException;
25 * Test to illustrate the basic use of Mockito VS the EXCEPTION_ANSWER.
27 * <p>Also useful as example to contrast this approach with the REAL_OR_EXCEPTION
28 * approach illustrated in the MikitoTest.
32 * @author Michael Vorburger
34 public class MockitoExampleTutorialTest {
36 interface SomeService {
40 String bar(String arg);
42 // Most methods on real world services have complex input (and output objects), not just int or String
43 int foobar(File file);
47 public void usingMockitoWithoutStubbing() {
48 SomeService service = mock(SomeService.class);
49 assertNull(service.bar("hulo"));
53 public void usingMockitoToStubSimpleCase() {
54 SomeService service = mock(SomeService.class);
55 when(service.foobar(any())).thenReturn(123);
56 assertEquals(123, service.foobar(new File("hello.txt")));
60 public void usingMockitoToStubComplexCase() {
61 SomeService service = mock(SomeService.class);
62 when(service.foobar(any())).thenAnswer(invocation -> {
63 File file = invocation.getArgument(0);
64 return "hello.txt".equals(file.getName()) ? 123 : 0;
66 assertEquals(0, service.foobar(new File("belo.txt")));
69 @Test(expected = UnstubbedMethodException.class)
70 public void usingMockitoExceptionException() {
71 SomeService service = mock(SomeService.class, exception());
76 public void usingMockitoNoExceptionIfStubbed() {
77 SomeService service = mock(SomeService.class, exception());
78 // NOT when(s.foobar(any())).thenReturn(123) BUT must be like this:
79 doReturn(123).when(service).foobar(any());
80 assertEquals(123, service.foobar(new File("hello.txt")));
81 assertThrows(UnstubbedMethodException.class, service::foo);
85 public void usingMockitoToStubComplexCaseAndExceptionIfNotStubbed() {
86 SomeService service = mock(SomeService.class, exception());
87 doAnswer(invocation -> {
88 File file = invocation.getArgument(0);
89 return "hello.txt".equals(file.getName()) ? 123 : 0;
90 }).when(service).foobar(any());
91 assertEquals(123, service.foobar(new File("hello.txt")));
92 assertEquals(0, service.foobar(new File("belo.txt")));