Best Mockito code snippet using org.mockito.Spy.init
Source:SpyAnnotationTest.java
...39 MockTranslator translator;40 @Rule41 public final ExpectedException shouldThrow = ExpectedException.none();42 @Test43 public void should_init_spy_by_instance() throws Exception {44 doReturn("foo").when(spiedList).get(10);45 assertEquals("foo", spiedList.get(10));46 assertTrue(spiedList.isEmpty());47 }48 @Test49 public void should_init_spy_and_automatically_create_instance() throws Exception {50 when(staticTypeWithNoArgConstructor.toString()).thenReturn("x");51 when(staticTypeWithoutDefinedConstructor.toString()).thenReturn("y");52 assertEquals("x", staticTypeWithNoArgConstructor.toString());53 assertEquals("y", staticTypeWithoutDefinedConstructor.toString());54 }55 @Test56 public void should_allow_spying_on_interfaces() throws Exception {57 class WithSpy {58 @Spy59 List<String> list;60 }61 WithSpy withSpy = new WithSpy();62 MockitoAnnotations.initMocks(withSpy);63 when(withSpy.list.size()).thenReturn(3);64 assertEquals(3, withSpy.list.size());65 }66 @Test67 public void should_allow_spying_on_interfaces_when_instance_is_concrete() throws Exception {68 class WithSpy {69 @Spy70 List<String> list = new LinkedList<String>();71 }72 WithSpy withSpy = new WithSpy();73 //when74 MockitoAnnotations.initMocks(withSpy);75 //then76 verify(withSpy.list, never()).clear();77 }78 @Test79 public void should_report_when_no_arg_less_constructor() throws Exception {80 class FailingSpy {81 @Spy82 NoValidConstructor noValidConstructor;83 }84 try {85 MockitoAnnotations.initMocks(new FailingSpy());86 fail();87 } catch (MockitoException e) {88 assertThat(e.getMessage()).contains("Please ensure that the type")89 .contains(NoValidConstructor.class.getSimpleName())90 .contains("has a no-arg constructor");91 }92 }93 @Test94 public void should_report_when_constructor_is_explosive() throws Exception {95 class FailingSpy {96 @Spy97 ThrowingConstructor throwingConstructor;98 }99 try {100 MockitoAnnotations.initMocks(new FailingSpy());101 fail();102 } catch (MockitoException e) {103 assertThat(e.getMessage()).contains("Unable to create mock instance");104 }105 }106 @Test107 public void should_spy_abstract_class() throws Exception {108 class SpyAbstractClass {109 @Spy110 AbstractList<String> list;111 List<String> asSingletonList(String s) {112 when(list.size()).thenReturn(1);113 when(list.get(0)).thenReturn(s);114 return list;115 }116 }117 SpyAbstractClass withSpy = new SpyAbstractClass();118 MockitoAnnotations.initMocks(withSpy);119 assertEquals(Arrays.asList("a"), withSpy.asSingletonList("a"));120 }121 @Test122 public void should_spy_inner_class() throws Exception {123 class WithMockAndSpy {124 @Spy125 private InnerStrength strength;126 @Mock127 private List<String> list;128 abstract class InnerStrength {129 private final String name;130 InnerStrength() {131 // Make sure that @Mock fields are always injected before @Spy fields.132 assertNotNull(list);133 // Make sure constructor is indeed called.134 this.name = "inner";135 }136 abstract String strength();137 String fullStrength() {138 return name + " " + strength();139 }140 }141 }142 WithMockAndSpy outer = new WithMockAndSpy();143 MockitoAnnotations.initMocks(outer);144 when(outer.strength.strength()).thenReturn("strength");145 assertEquals("inner strength", outer.strength.fullStrength());146 }147 @Test(expected = IndexOutOfBoundsException.class)148 public void should_reset_spy() throws Exception {149 spiedList.get(10); // see shouldInitSpy150 }151 @Test152 public void should_report_when_enclosing_instance_is_needed() throws Exception {153 class Outer {154 class Inner {155 }156 }157 class WithSpy {158 @Spy159 private Outer.Inner inner;160 }161 try {162 MockitoAnnotations.initMocks(new WithSpy());163 fail();164 } catch (MockitoException e) {165 assertThat(e).hasMessageContaining("@Spy annotation can only initialize inner classes");166 }167 }168 @Test169 public void should_report_private_inner_not_supported() throws Exception {170 try {171 MockitoAnnotations.initMocks(new WithInnerPrivate());172 fail();173 } catch (MockitoException e) {174 // Currently fails at instantiation time, because the mock subclass don't have the175 // 1-arg constructor expected for the outerclass.176 // org.mockito.internal.creation.instance.ConstructorInstantiator.withParams()177 assertThat(e).hasMessageContaining("Unable to initialize @Spy annotated field 'spy_field'")178 .hasMessageContaining(WithInnerPrivate.InnerPrivate.class.getSimpleName());179 }180 }181 @Test182 public void should_report_private_abstract_inner_not_supported() throws Exception {183 try {184 MockitoAnnotations.initMocks(new WithInnerPrivateAbstract());185 fail();186 } catch (MockitoException e) {187 assertThat(e).hasMessageContaining("@Spy annotation can't initialize private abstract inner classes")188 .hasMessageContaining(WithInnerPrivateAbstract.class.getSimpleName())189 .hasMessageContaining(WithInnerPrivateAbstract.InnerPrivateAbstract.class.getSimpleName())190 .hasMessageContaining("You should augment the visibility of this inner class");191 }192 }193 @Test194 public void should_report_private_static_abstract_inner_not_supported() throws Exception {195 try {196 MockitoAnnotations.initMocks(new WithInnerPrivateStaticAbstract());197 fail();198 } catch (MockitoException e) {199 assertThat(e).hasMessageContaining("@Spy annotation can't initialize private abstract inner classes")200 .hasMessageContaining(WithInnerPrivateStaticAbstract.class.getSimpleName())201 .hasMessageContaining(WithInnerPrivateStaticAbstract.InnerPrivateStaticAbstract.class.getSimpleName())202 .hasMessageContaining("You should augment the visibility of this inner class");203 }204 }205 @Test206 public void should_be_able_to_stub_and_verify_via_varargs_for_list_params() throws Exception {207 // You can stub with varargs.208 when(translator.translate("hello", "mockito")).thenReturn(Arrays.asList("you", "too"));209 // Pretend the prod code will call translate(List<String>) with these elements.210 assertThat(translator.translate(Arrays.asList("hello", "mockito"))).containsExactly("you", "too");211 assertThat(translator.translate(Arrays.asList("not stubbed"))).isEmpty();212 // You can verify with varargs.213 verify(translator).translate("hello", "mockito");...
init
Using AI Code Generation
1[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-example ---2[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ mockito-example ---3[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mockito-example ---4[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ mockito-example ---5[INFO] --- maven-failsafe-plugin:2.12.4:integration-test (default) @ mockito-example ---6[INFO] --- maven-failsafe-plugin:2.12.4:verify (default) @ mockito-example ---7[INFO] --- maven-install-plugin:2.4:install (default-install) @ mockito-example ---
init
Using AI Code Generation
1import org.mockito.Spy2import org.mockito.Mockito.mock3import org.mockito.Mockito.spy4import org.mockito.Mockito.verify5import org.mockito.Mockito.times6import org.mockito.Mockito.doReturn7import org.mockito.Mockito.doThrow8import org.mockito.Mockito.doNothing9import org.mockito.Mockito.doAnswer10import org.mockito.Mockito.doNothing11import org.mockito.Mockito.doCallRealMethod12import org.mockito.Mockito.doAnswer13import org.mockito.Mockito.doReturn14import org.mockito.Mockito.doThrow15import org.mockito.invocation.InvocationOnMock16import org.mockito.stubbing.Answer17import org.mockito.stubbing.Stubber18import org.mockito.Mockito.*19import org.mockito.Mockito.mock20import org.mockito.Mockito.spy21import org.mockito.Mockito.verify22import org.mockito.Mockito.times23import org.mockito.Mockito.doReturn24import org.mockito.Mockito.doThrow25import org.mockito.Mockito.doNothing26import org.mockito.Mockito.doAnswer27import org.mockito.Mockito.doNothing28import org.mockito.Mockito.doCallRealMethod29import org.mockito.Mockito.doAnswer30import org.mockito.Mockito.doReturn31import org.mockito.Mockito.doThrow32import org.mockito.invocation.InvocationOnMock33import org.mockito.stubbing.Answer34import org.mockito.stubbing.Stubber35import org.mockito.Matchers.*36import org.mockito.Matchers.anyInt37import org.mockito.Matchers.anyString38import org.mockito.Matchers.any39import org.mockito.Matchers.anyVararg40import org.mockito.Matchers.anyCollection41import org.mockito.Matchers.anyCollectionOf42import org.mockito.Matchers.anyIterable43import org.mockito.Matchers.anyList44import org.mockito.Matchers.anyMap45import org.mockito.Matchers.anyMapOf46import org.mockito.Matchers.anySet47import org.mockito.Matchers.anySetOf48import org.mockito.Matchers.anyVararg49import org.mockito.Matchers.argThat50import org.mockito.Matchers.contains51import org.mockito.Matchers.eq52import org.mockito.Matchers.isA53import org.mockito.Matchers.isNull54import org.mockito.Matchers.notNull55import org.mockito.Matchers.refEq56import org.mockito.Matchers.same57import org.mockito.ArgumentMatchers.*58import org.mockito.ArgumentMatchers.anyInt59import org.mockito.ArgumentMatchers.anyString60import org.mockito.ArgumentMatchers.any61import org.mockito.ArgumentMatchers.anyVararg62import org.mockito.ArgumentMatchers.anyCollection63import org.mockito.ArgumentMatchers.anyCollectionOf64import org.mockito.ArgumentMatchers.anyIterable65import org.mockito.ArgumentMatchers.any
init
Using AI Code Generation
1import org.mockito.Spy;2import org.mockito.MockitoAnnotations;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.junit.Before;6import org.junit.Test;7import static org.mockito.Mockito.*;8import static org.junit.Assert.*;9public class MockitoSpyTest {10 private List<String> spyList;11 private List<String> list;12 private List<String> mockList;13 public void init() {14 MockitoAnnotations.initMocks(this);15 }16 public void testSpy() {17 spyList.add("one");18 spyList.add("two");19 verify(spyList).add("one");20 verify(spyList).add("two");21 assertEquals(2, spyList.size());22 assertEquals(0, list.size());23 assertEquals(0, mockList.size());24 }25}26You have a Mockito spy() on a final class that is not a mock. 27You have a Mockito spy() on a final class th
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!