1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 6package org.mockitousage.basicapi; 7 8import org.junit.Test; 9import org.mockito.InjectMocks; 10import org.mockito.Mockito; 11import org.mockito.MockitoAnnotations; 12import org.mockito.exceptions.base.MockitoException; 13import org.mockito.exceptions.verification.SmartNullPointerException; 14import org.mockito.internal.debugging.LocationImpl; 15import org.mockitousage.IMethods; 16import org.mockitoutil.TestBase; 17 18import java.util.LinkedList; 19import java.util.List; 20import java.util.Set; 21import java.util.concurrent.TimeUnit; 22 23import static junit.framework.TestCase.*; 24import static org.assertj.core.api.Assertions.assertThat; 25import static org.mockito.Mockito.*; 26 27@SuppressWarnings("unchecked") 28public class MocksCreationTest extends TestBase { 29 30 private class HasPrivateConstructor {} 31 32 @Test 33 public void shouldCreateMockWhenConstructorIsPrivate() { 34 assertNotNull(Mockito.mock(HasPrivateConstructor.class)); 35 } 36 37 @Test 38 public void shouldCombineMockNameAndSmartNulls() { 39 //given 40 IMethods mock = mock(IMethods.class, withSettings() 41 .defaultAnswer(RETURNS_SMART_NULLS) 42 .name("great mockie")); 43 44 //when 45 IMethods smartNull = mock.iMethodsReturningMethod(); 46 String name = mock.toString(); 47 48 //then 49 assertThat(name).contains("great mockie"); 50 //and 51 try { 52 smartNull.simpleMethod(); 53 fail(); 54 } catch(SmartNullPointerException e) {} 55 } 56 57 @Test 58 public void shouldCombineMockNameAndExtraInterfaces() { 59 //given 60 IMethods mock = mock(IMethods.class, withSettings() 61 .extraInterfaces(List.class) 62 .name("great mockie")); 63 64 //when 65 String name = mock.toString(); 66 67 //then 68 assertThat(name).contains("great mockie"); 69 //and 70 assertTrue(mock instanceof List); 71 } 72 73 @Test 74 public void shouldSpecifyMockNameViaSettings() { 75 //given 76 IMethods mock = mock(IMethods.class, withSettings().name("great mockie")); 77 78 //when 79 String name = mock.toString(); 80 81 //then 82 assertThat(name).contains("great mockie"); 83 } 84 85 @Test 86 public void shouldScreamWhenSpyCreatedWithWrongType() { 87 //given 88 List list = new LinkedList(); 89 try { 90 //when 91 mock(List.class, withSettings().spiedInstance(list)); 92 fail(); 93 //then 94 } catch (MockitoException e) {} 95 } 96 97 @Test 98 public void shouldAllowCreatingSpiesWithCorrectType() { 99 List list = new LinkedList(); 100 mock(LinkedList.class, withSettings().spiedInstance(list)); 101 } 102 103 @Test 104 public void shouldAllowInlineMockCreation() throws Exception { 105 when(mock(Set.class).isEmpty()).thenReturn(false); 106 } 107 108} 109