@Test public void jsr107LoaderInitFailureClosesExpiry() throws Exception { ExpiryPolicy expiryPolicy = mock(ExpiryPolicy.class, new MockSettingsImpl<>().extraInterfaces(Closeable.class)); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>(); Factory<CacheLoader<Object, Object>> factory = throwingFactory(); configuration.setExpiryPolicyFactory(factoryOf(expiryPolicy)) .setReadThrough(true) .setCacheLoaderFactory(factory); try { merger.mergeConfigurations("cache", configuration); fail("Loader factory should have thrown"); } catch (MultiCacheException mce) { verify((Closeable) expiryPolicy).close(); } }
@Test public void jsr107ListenerFactoryInitFailureClosesExpiryLoader() throws Exception { ExpiryPolicy expiryPolicy = mock(ExpiryPolicy.class, new MockSettingsImpl<>().extraInterfaces(Closeable.class)); CacheLoader<Object, Object> loader = mock(CacheLoader.class, new MockSettingsImpl<>().extraInterfaces(Closeable.class)); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>(); configuration.setExpiryPolicyFactory(factoryOf(expiryPolicy)) .setReadThrough(true) .setCacheLoaderFactory(factoryOf(loader)) .addCacheEntryListenerConfiguration(new ThrowingCacheEntryListenerConfiguration()); try { merger.mergeConfigurations("cache", configuration); fail("Loader factory should have thrown"); } catch (MultiCacheException mce) { verify((Closeable) expiryPolicy).close(); verify((Closeable) loader).close(); } }
@SuppressWarnings("unchecked") @Test public void closesAllResources() throws Exception { Jsr107CacheLoaderWriter<Object, Object> loaderWriter = mock(Jsr107CacheLoaderWriter.class, new MockSettingsImpl<>().extraInterfaces(Closeable.class)); Eh107Expiry<Object, Object> expiry = mock(Eh107Expiry.class, new MockSettingsImpl<>().extraInterfaces(Closeable.class)); CacheEntryListenerConfiguration<Object, Object> listenerConfiguration = mock(CacheEntryListenerConfiguration.class); ListenerResources<Object, Object> listenerResources = mock(ListenerResources.class); Map<CacheEntryListenerConfiguration<Object, Object>, ListenerResources<Object, Object>> map = new HashMap<>(); map.put(listenerConfiguration, listenerResources); CacheResources<Object, Object> cacheResources = new CacheResources<>("cache", loaderWriter, expiry, map); cacheResources.closeResources(new MultiCacheException()); verify((Closeable) loaderWriter).close(); verify((Closeable) expiry).close(); verify(listenerResources).close(); }
@Test public void shouldRemoveVerificationModeEvenWhenInvalidMatchers() throws Throwable { // given Invocation invocation = new InvocationBuilder().toInvocation(); @SuppressWarnings("rawtypes") MockHandlerImpl<?> handler = new MockHandlerImpl(new MockSettingsImpl()); handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce()); handler.matchersBinder = new MatchersBinder() { public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) { throw new InvalidUseOfMatchersException(); } }; try { // when handler.handle(invocation); // then fail(); } catch (InvalidUseOfMatchersException e) { } assertNull(handler.mockingProgress.pullVerificationMode()); }
@Test public void shouldCreateSerializableMethodProxyIfIsSerializableMock() throws Exception { MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings().serializable()); MethodProxy methodProxy = MethodProxy.create(String.class, String.class, "", "toString", "toString"); // when MockitoMethodProxy mockitoMethodProxy = filter.createMockitoMethodProxy(methodProxy); // then assertThat(mockitoMethodProxy, instanceOf(SerializableMockitoMethodProxy.class)); }
@Test public void shouldCreateNONSerializableMethodProxyIfIsNotSerializableMock() throws Exception { MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings()); MethodProxy methodProxy = MethodProxy.create(String.class, String.class, "", "toString", "toString"); // when MockitoMethodProxy mockitoMethodProxy = filter.createMockitoMethodProxy(methodProxy); // then assertThat(mockitoMethodProxy, instanceOf(DelegatingMockitoMethodProxy.class)); }
@Test public void shouldCreateSerializableMethodIfIsSerializableMock() throws Exception { MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings().serializable()); Method method = new InvocationBuilder().toInvocation().getMethod(); // when MockitoMethod mockitoMethod = filter.createMockitoMethod(method); // then assertThat(mockitoMethod, instanceOf(SerializableMethod.class)); }
@Test public void shouldCreateJustDelegatingMethodIfIsNotSerializableMock() throws Exception { MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings()); Method method = new InvocationBuilder().toInvocation().getMethod(); // when MockitoMethod mockitoMethod = filter.createMockitoMethod(method); // then assertThat(mockitoMethod, instanceOf(DelegatingMethod.class)); }
@Test public void testAddBreakpoint() throws Exception { MockSettings mockSettings = new MockSettingsImpl<>().defaultAnswer(RETURNS_SMART_NULLS).extraInterfaces(Resource.class); Project project = mock(Project.class); when(optional.isPresent()).thenReturn(true); when(optional.get()).thenReturn(project); when(project.getPath()).thenReturn(PATH); VirtualFile virtualFile = mock(VirtualFile.class, mockSettings); Path path = mock(Path.class); when(path.toString()).thenReturn(PATH); when(virtualFile.getLocation()).thenReturn(path); when(virtualFile.toString()).thenReturn(PATH); Resource resource = (Resource) virtualFile; when(resource.getRelatedProject()).thenReturn(optional); doReturn(promiseVoid).when(service).addBreakpoint(SESSION_ID, breakpointDto); doReturn(promiseVoid).when(promiseVoid).then((Operation<Void>) any()); doReturn(breakpointDto).when(debugger).toDto(any(Breakpoint.class)); debugger.addBreakpoint(breakpointDto); verify(service).addBreakpoint(SESSION_ID, breakpointDto); verify(promiseVoid).then(operationVoidCaptor.capture()); operationVoidCaptor.getValue().apply(null); verify(observer).onBreakpointAdded(breakpointCaptor.capture()); assertEquals(breakpointCaptor.getValue(), breakpointDto); verify(promiseVoid).catchError(operationPromiseErrorCaptor.capture()); operationPromiseErrorCaptor.getValue().apply(promiseError); verify(promiseError).getMessage(); }
Object returnValueFor(Class<?> clazz) { if (!ClassImposterizer.INSTANCE.canImposterise(clazz)) { return null; } return mockitoCore.mock(clazz, new MockSettingsImpl().defaultAnswer(this)); }
public <T> T createMock(Class<T> classToMock, MockSettingsImpl settings) { creationValidator.validateType(classToMock); creationValidator.validateExtraInterfaces(classToMock, settings.getExtraInterfaces()); creationValidator.validateMockedType(classToMock, settings.getSpiedInstance()); settings.initiateMockName(classToMock); MockHandler<T> mockHandler = new MockHandler<T>(settings); MethodInterceptorFilter filter = new MethodInterceptorFilter(mockHandler, settings); Class<?>[] interfaces = settings.getExtraInterfaces(); Class<?>[] ancillaryTypes; if (settings.isSerializable()) { ancillaryTypes = interfaces == null ? new Class<?>[] {Serializable.class} : new ArrayUtils().concat(interfaces, Serializable.class); } else { ancillaryTypes = interfaces == null ? new Class<?>[0] : interfaces; } Object spiedInstance = settings.getSpiedInstance(); T mock = ClassImposterizer.INSTANCE.imposterise(filter, classToMock, ancillaryTypes); if (spiedInstance != null) { new LenientCopyTool().copyToMock(spiedInstance, mock); } return mock; }
public <T> void resetMock(T mock) { MockHandlerInterface<T> oldMockHandler = getMockHandler(mock); MockHandler<T> newMockHandler = new MockHandler<T>(oldMockHandler); MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) withSettings().defaultAnswer(RETURNS_DEFAULTS)); ((Factory) mock).setCallback(0, newFilter); }
@Test public void shouldNotifyListenerWhenMockingStarted() throws Exception { //given MockingStartedListener listener = mock(MockingStartedListener.class); mockingProgress.setListener(listener); //when mockingProgress.mockingStarted("foo", List.class, new MockSettingsImpl()); //then verify(listener).mockingStarted(eq("foo"), eq(List.class), (MockSettingsImpl) notNull()); }
@Test public void shouldValidate() { //given assertFalse(creationValidator.extraInterfacesValidated); assertFalse(creationValidator.typeValidated); //when mockUtil.createMock(IMethods.class, new MockSettingsImpl()); //then assertTrue(creationValidator.extraInterfacesValidated); assertTrue(creationValidator.typeValidated); }
@Test public void shouldStartingMockSettingsContainDefaultBehavior() { //when MockSettingsImpl settings = (MockSettingsImpl) Mockito.withSettings(); //then assertEquals(Mockito.RETURNS_DEFAULTS, settings.getDefaultAnswer()); }
Object returnValueFor(Class<?> clazz) { if (!mockitoCore.isTypeMockable(clazz)) { return null; } return mockitoCore.mock(clazz, new MockSettingsImpl().defaultAnswer(this)); }
@Before public void setup() { state = new MockingProgressImpl(); invocationContainerImpl = new InvocationContainerImpl(state, new MockSettingsImpl()); invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationBuilder().toInvocationMatcher()); invocationContainerImplStubOnly = new InvocationContainerImpl(state, new MockSettingsImpl().stubOnly()); invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationBuilder().toInvocationMatcher()); simpleMethod = new InvocationBuilder().simpleMethod().toInvocation(); }
@Before public void setUp() throws Exception { notifier = new InvocationNotifierHandler( mockHandler, (MockSettingsImpl) new MockSettingsImpl().invocationListeners(customListener, listener1, listener2) ); }
@Test //see issue 331 public void handle_result_must_not_be_null_for_primitives() throws Throwable { //given: MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(null)); InternalMockHandler handler = new MockHandlerFactory().create(settings); mock.intReturningMethod(); Invocation invocation = super.getLastInvocation(); //when: Object result = handler.handle(invocation); //then null value is not a valid result for a primitive assertNotNull(result); assertEquals(0, result); }
@Test //see issue 331 public void valid_handle_result_is_permitted() throws Throwable { //given: MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(123)); InternalMockHandler handler = new MockHandlerFactory().create(settings); mock.intReturningMethod(); Invocation invocation = super.getLastInvocation(); //when: Object result = handler.handle(invocation); //then assertEquals(123, result); }
private MockHandlerImpl<?> createHandlerWithListeners(InvocationListener... listener) { @SuppressWarnings("rawtypes") MockHandlerImpl<?> handler = new MockHandlerImpl(mock(MockSettingsImpl.class)); handler.matchersBinder = mock(MatchersBinder.class); given(handler.getMockSettings().getInvocationListeners()).willReturn(Arrays.asList(listener)); return handler; }
public MockCreationSettings getMockSettings() { final MockSettingsImpl mockSettings = new MockSettingsImpl(); mockSettings.setMockName(new MockNameImpl(mock.getName())); mockSettings.setTypeToMock(mock); return mockSettings; }
public MockHandler(MockSettingsImpl mockSettings) { this.mockSettings = mockSettings; this.mockingProgress = new ThreadSafeMockingProgress(); this.matchersBinder = new MatchersBinder(); this.invocationContainerImpl = new InvocationContainerImpl(mockingProgress); }
MockHandler() { this(new MockSettingsImpl()); }
public MockSettingsImpl getMockSettings() { return mockSettings; }
/** * Allows mock creation with additional mock settings. * <p> * Don't use it too often. * Consider writing simple tests that use simple mocks. * Repeat after me: simple tests push simple, KISSy, readable & maintainable code. * If you cannot write a test in a simple way - refactor the code under test. * <p> * Examples of mock settings: * <pre> * //Creates mock with different default answer & name * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie")); * * //Creates mock with different default answer, descriptive name and extra interfaces * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie") * .extraInterfaces(Bar.class)); * </pre> * {@link MockSettings} has been introduced for two reasons. * Firstly, to make it easy to add another mock settings when the demand comes. * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods. * <p> * See javadoc for {@link MockSettings} to learn about possible mock settings. * <p> * * @return mock settings instance with defaults. */ public static MockSettings withSettings() { return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS); }
/** * Allows mock creation with additional mock settings. * <p> * Don't use it too often. * Consider writing simple tests that use simple mocks. * Repeat after me: simple tests push simple, KISSy, readable & maintainable code. * If you cannot write a test in a simple way - refactor the code under test. * <p> * Examples of mock settings: * <pre class="code"><code class="java"> * //Creates mock with different default answer & name * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie")); * * //Creates mock with different default answer, descriptive name and extra interfaces * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie") * .extraInterfaces(Bar.class)); * </code></pre> * {@link MockSettings} has been introduced for two reasons. * Firstly, to make it easy to add another mock settings when the demand comes. * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods. * <p> * See javadoc for {@link MockSettings} to learn about possible mock settings. * <p> * * @return mock settings instance with defaults. */ public static MockSettings withSettings() { return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS); }
MockSettingsImpl getMockSettings();