private Operation<Void, UpdateDatabaseDdlMetadata> mockOperation(boolean error) { @SuppressWarnings("unchecked") Operation<Void, UpdateDatabaseDdlMetadata> op = mock(Operation.class); when(op.getName()).then(new Returns("TEST_OPERATION")); when(op.isDone()).then(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return reportDone; } }); when(op.reload()).then(new Returns(op)); if (error) when(op.getResult()).thenThrow( SpannerExceptionFactory.newSpannerException(ErrorCode.INVALID_ARGUMENT, "Some exception")); else when(op.getResult()).then(new Returns(null)); UpdateDatabaseDdlMetadata metadata = UpdateDatabaseDdlMetadata.getDefaultInstance(); when(op.getMetadata()).then(new Returns(metadata)); return op; }
@Test public void testAutoBatch() throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { CloudSpannerConnection connection = createConnection(); Mockito.doCallRealMethod().when(connection).addAutoBatchedDdlOperation(Mockito.anyString()); Mockito.doCallRealMethod().when(connection).clearAutoBatchedDdlOperations(); Mockito.doCallRealMethod().when(connection).getAutoBatchedDdlOperations(); Mockito.when(connection.isAutoBatchDdlOperations()).then(new Returns(true)); Field field = CloudSpannerConnection.class.getDeclaredField("autoBatchedDdlOperations"); field.setAccessible(true); field.set(connection, new ArrayList<String>()); CloudSpannerStatement statement = connection.createStatement(); assertEquals(0, connection.getAutoBatchedDdlOperations().size()); statement.execute(BATCH_DDL); assertEquals(1, connection.getAutoBatchedDdlOperations().size()); statement.execute(BATCH_DML); assertEquals(1, connection.getAutoBatchedDdlOperations().size()); statement.execute("EXECUTE_DDL_BATCH"); assertEquals(0, connection.getAutoBatchedDdlOperations().size()); }
private static void mockXAMethods(CloudSpannerConnection connection) throws SQLException { String checkTable = null; try { Field field = CloudSpannerXAConnection.class.getDeclaredField("CHECK_TABLE_EXISTENCE"); field.setAccessible(true); checkTable = (String) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } CloudSpannerPreparedStatement ps = Mockito.mock(CloudSpannerPreparedStatement.class); CloudSpannerResultSet rs = Mockito.mock(CloudSpannerResultSet.class); Mockito.when(rs.next()).thenReturn(true, false); Mockito.when(connection.prepareStatement(checkTable)).thenAnswer(new Returns(ps)); Mockito.when(ps.executeQuery()).thenAnswer(new Returns(rs)); }
@Test public void onExceptionOnTheFirstTime() throws Exception { DiskRawQueue queue = mock(DiskRawQueue.class); Lenient.Op op = mock(Lenient.Op.class); Lenient lenient = new Lenient(queue); InOrder orderly = inOrder(queue, op); when(op.call()) .thenAnswer(new ThrowsException(new Error("abc"))) .thenAnswer(new Returns(42L)); assertThat(lenient.perform(op)).isEqualTo(42); orderly.verify(op).call(); orderly.verify(queue).reopen(); }
/** * Tests that an array of values is included if the argument type is annotated with @Config and there * are values of that type in the config master. if there is no value selected there the selected item * isn't included (empty or null?) */ @Test public void configArgNoSelection() { AvailableImplementations availableImplementations = new AvailableImplementationsImpl(); availableImplementations.register(UsesConfig.class); FunctionModelConfig config = new FunctionModelConfig(availableImplementations.getDefaultImplementations()); FunctionModel model = FunctionModel.forFunction(FOO_META, config); ConfigMaster configMaster = mock(ConfigMaster.class); ConfigSearchRequest<?> searchRequest = new ConfigSearchRequest<>(); searchRequest.setType(ConfigObject.class); List<ConfigDocument> configs = Lists.newArrayList(configDocument("foo"), configDocument("bar"), configDocument("baz")); when(configMaster.search(searchRequest)).thenAnswer(new Returns(new ConfigSearchResult<>(configs))); ConfigJsonBuilder builder = new ConfigJsonBuilder(mock(AvailableOutputs.class), availableImplementations, configMaster, new DefaultArgumentConverter()); Map<String, Object> functionJson = builder.getConfigPageModel(COLUMN_NAME, config, null, null, model); checkJson(functionJson, "configArgNoSelection"); }
/** * Tests that an array of values is included if the argument type is annotated with @Config and there * are values of that type in the config master. If there is a value selected it is included * TODO enable this test once the config link API has been changed to include the link target's name */ @Test(enabled = false) public void configArgValueSelected() { AvailableImplementations availableImplementations = new AvailableImplementationsImpl(); availableImplementations.register(UsesConfig.class); ConfigLink<ConfigObject> configLink = ConfigLink.resolvable("bar", ConfigObject.class); FunctionModelConfig config = config(implementations(Fn.class, UsesConfig.class), arguments(function(UsesConfig.class, argument("configArg", configLink)))); FunctionModel model = FunctionModel.forFunction(FOO_META, config); ConfigMaster configMaster = mock(ConfigMaster.class); ConfigSearchRequest<?> searchRequest = new ConfigSearchRequest<>(); searchRequest.setType(ConfigObject.class); List<ConfigDocument> configs = Lists.newArrayList(configDocument("foo"), configDocument("bar"), configDocument("baz")); when(configMaster.search(searchRequest)).thenAnswer(new Returns(new ConfigSearchResult<>(configs))); ConfigJsonBuilder builder = new ConfigJsonBuilder(mock(AvailableOutputs.class), availableImplementations, configMaster, new DefaultArgumentConverter()); Map<String, Object> json = builder.getConfigPageModel(COLUMN_NAME, config, null, null, model); checkJson(json, "configArgNoSelection"); }
@Test public void shouldGetResultsForMethods() throws Throwable { invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod)); invocationContainerImpl.addAnswer(new Returns("simpleMethod")); Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation(); invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod)); invocationContainerImpl.addAnswer(new ThrowsException(new MyException())); assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod)); try { invocationContainerImpl.answerTo(differentMethod); fail(); } catch (MyException e) {} }
@Test public void should_get_results_for_methods() throws Throwable { invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod)); invocationContainerImpl.addAnswer(new Returns("simpleMethod")); Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation(); invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod)); invocationContainerImpl.addAnswer(new ThrowsException(new MyException())); assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod)); try { invocationContainerImpl.answerTo(differentMethod); fail(); } catch (MyException e) {} }
@Test public void should_get_results_for_methods_stub_only() throws Throwable { invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod)); invocationContainerImplStubOnly.addAnswer(new Returns("simpleMethod")); Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation(); invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod)); invocationContainerImplStubOnly.addAnswer(new ThrowsException(new MyException())); assertEquals("simpleMethod", invocationContainerImplStubOnly.answerTo(simpleMethod)); try { invocationContainerImplStubOnly.answerTo(differentMethod); fail(); } catch (MyException e) {} }
private TestSubject createTestSubject() { MockTransactionRunner runner = new MockTransactionRunner(); DatabaseClient dbClient = mock(DatabaseClient.class); when(dbClient.readWriteTransaction()).then(new Returns(runner)); return new TestSubject(new TransactionThread(dbClient), runner.mock); }
@Test public void testSingleInsertStatementOnReadOnlyConnection() throws SQLException { thrown.expect(CloudSpannerSQLException.class); thrown.expectMessage("The connection is in read-only mode. Mutations are not allowed."); String sql = "INSERT INTO FOO (ID, COL1, COL2) VALUES (?, ?, ?)"; CloudSpannerPreparedStatement ps = CloudSpannerTestObjects.createPreparedStatement(sql); Mockito.when(ps.getConnection().isReadOnly()).thenAnswer(new Returns(true)); ps.executeUpdate(); }
@Test public void testBulkInsertStatementOnReadOnlyConnection() throws SQLException { thrown.expect(CloudSpannerSQLException.class); thrown.expectMessage("The connection is in read-only mode. Mutations are not allowed."); String sql = "INSERT INTO FOO (ID, COL1, COL2) SELECT 1, 2, 3 FROM FOO"; CloudSpannerPreparedStatement ps = CloudSpannerTestObjects.createPreparedStatement(sql); Mockito.when(ps.getConnection().isReadOnly()).thenAnswer(new Returns(true)); ps.executeUpdate(); }
@Test public void testBatchedInsertStatementOnReadOnlyConnection() throws SQLException { thrown.expect(CloudSpannerSQLException.class); thrown.expectMessage("Connection is in read-only mode. Mutations are not allowed"); String sql = "INSERT INTO FOO (ID, COL1, COL2) VALUES (?, ?, ?)"; CloudSpannerPreparedStatement ps = CloudSpannerTestObjects.createPreparedStatement(sql); ps.addBatch(); Mockito.when(ps.getConnection().isReadOnly()).thenAnswer(new Returns(true)); ps.executeBatch(); }
public static CloudSpannerConnection create(String url) throws SQLException { ConnectionProperties properties = ConnectionProperties.parse(url); CloudSpannerConnection connection = mock(CloudSpannerConnection.class); when(connection.getSimulateMajorVersion()).then(new Returns(null)); when(connection.getSimulateMinorVersion()).then(new Returns(null)); when(connection.getUrl()).thenAnswer(new Returns(url)); when(connection.getProductName()).thenAnswer(new Returns(properties.productName)); when(connection.getNodeCount()).thenAnswer(new Returns(1)); return connection; }
public static CloudSpannerConnection createConnection() throws SQLException { CloudSpannerConnection connection = Mockito.mock(CloudSpannerConnection.class); Mockito.doCallRealMethod().when(connection).setAutoCommit(Mockito.anyBoolean()); Mockito.when(connection.getAutoCommit()).thenCallRealMethod(); connection.setAutoCommit(false); Mockito.when(connection.isAllowExtendedMode()).thenAnswer(new Returns(true)); Mockito.when(connection.createArrayOf(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); CloudSpannerDatabaseMetaData metadata = createMetaData(); Mockito.when(connection.getMetaData()).thenReturn(metadata); CloudSpannerTransaction transaction = Mockito.mock(CloudSpannerTransaction.class); Mockito.when(transaction.executeQuery(Mockito.any())) .thenReturn(Mockito.mock(com.google.cloud.spanner.ResultSet.class)); Mockito.when(connection.getTransaction()).thenReturn(transaction); TableKeyMetaData tableFoo = Mockito.mock(TableKeyMetaData.class); Mockito.when(tableFoo.getKeyColumns()).thenAnswer(new Returns(Arrays.asList("ID"))); Mockito.when(connection .getTable(Mockito.matches(Pattern.compile("FOO", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)))) .thenAnswer(new Returns(tableFoo)); TableKeyMetaData tableBar = Mockito.mock(TableKeyMetaData.class); Mockito.when(tableBar.getKeyColumns()).thenAnswer(new Returns(Arrays.asList("ID1", "ID2"))); Mockito.when(connection .getTable(Mockito.matches(Pattern.compile("BAR", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)))) .thenAnswer(new Returns(tableBar)); Mockito.when(connection.getLogger()).thenAnswer(new Returns(new Logger())); mockXAMethods(connection); return connection; }
@Test public void createEntityTypeImplicitRenderer() { final String expectedRendering = "EXPECTED"; final TestEntity originalValue = new TestEntity(); originalValue.setId(1L); when(renderer.render(originalValue, DEFAULT_LOCALE)).thenReturn(expectedRendering); when(rendererService.findRenderer(TestEntity.class)).then(/* Bypass generics with an Answer */ new Returns(renderer)); HistoryValue expectedValue = new HistoryValue(expectedRendering, GenericEntityReference.of(originalValue)); assertEquals(expectedValue, historyValueService.create(originalValue)); }
@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); }
@Test public void renderHistoryValueImplicitRendererWithRetrieval() { final String expectedRendering = "EXPECTED"; TestEntity testEntity = new TestEntity(); GenericEntityReference<Long, TestEntity> presentEntityReference = GenericEntityReference.of(TestEntity.class, 1L); HistoryValue historyValue = new HistoryValue("UNEXPECTED", presentEntityReference); when(entityService.getEntity(presentEntityReference)).thenReturn(testEntity); when(renderer.render(testEntity, DEFAULT_LOCALE)).thenReturn(expectedRendering); when(rendererService.findRenderer(TestEntity.class)).then(/* Bypass generics with an Answer */ new Returns(renderer)); assertEquals(expectedRendering, historyValueService.render(historyValue, DEFAULT_LOCALE)); }
public Stubber doReturn(Object toBeReturned) { answers.add(new Returns(toBeReturned)); return this; }
public OngoingStubbing<T> thenReturn(T value) { return thenAnswer(new Returns(value)); }
public DeprecatedOngoingStubbing<T> toReturn(T value) { return toAnswer(new Returns(value)); }
@Test public void shouldFinishStubbingOnAddingReturnValue() throws Exception { state.stubbingStarted(); invocationContainerImpl.addAnswer(new Returns("test")); state.validateState(); }
@Test public void should_finish_stubbing_on_adding_return_value() throws Exception { state.stubbingStarted(); invocationContainerImpl.addAnswer(new Returns("test")); state.validateState(); }
@Test public void createMiscTypeImplicitRenderer() { final String expectedRendering = "EXPECTED"; final Object originalValue = new Object(); when(renderer.render(originalValue, DEFAULT_LOCALE)).thenReturn(expectedRendering); when(rendererService.findRenderer(Object.class)).then(/* Bypass generics with an Answer */ new Returns(renderer)); HistoryValue expectedValue = new HistoryValue(expectedRendering); assertEquals(expectedValue, historyValueService.create(originalValue)); }
/** * Use doReturn() in those rare occasions when you cannot use * {@link Mockito#when(Object)}. * <p> * <b>Beware that {@link Mockito#when(Object)} is always recommended for * stubbing because it is argument type-safe and more readable</b> * (especially when stubbing consecutive calls). * <p> * Here are those rare occasions when doReturn() comes handy: * <p> * * 1. When spying real objects and calling real methods on a spy brings side * effects * * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing: * doReturn("foo").when(spy).get(0); * </pre> * * 2. Overriding a previous exception-stubbing: * * <pre> * when(mock.foo()).thenThrow(new RuntimeException()); * * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar"); * * //You have to use doReturn() for stubbing: * doReturn("bar").when(mock).foo(); * </pre> * * Above scenarios shows a tradeoff of Mockito's ellegant syntax. Note that * the scenarios are very rare, though. Spying should be sporadic and * overriding exception-stubbing is very rare. * <p> * See examples in javadoc for {@link Mockito} class * * @param toBeReturned * to be returned when the stubbed method is called * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doReturn(Object toBeReturned) { return POWERMOCKITO_CORE.doAnswer(new Returns(toBeReturned)); }
/** * Use doReturn() in those rare occasions when you cannot use {@link Mockito#when(Object)}. * <p> * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe * and more readable</b> (especially when stubbing consecutive calls). * <p> * Here are those rare occasions when doReturn() comes handy: * <p> * * 1. When spying real objects and calling real methods on a spy brings side effects * * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing: * doReturn("foo").when(spy).get(0); * </pre> * * 2. Overriding a previous exception-stubbing: * * <pre> * when(mock.foo()).thenThrow(new RuntimeException()); * * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar"); * * //You have to use doReturn() for stubbing: * doReturn("bar").when(mock).foo(); * </pre> * * Above scenarios shows a tradeoff of Mockito's ellegant syntax. Note that the scenarios are very rare, though. * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general * overridding stubbing is a potential code smell that points out too much stubbing. * <p> * See examples in javadoc for {@link Mockito} class * * @param toBeReturned to be returned when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doReturn(Object toBeReturned) { return MOCKITO_CORE.doAnswer(new Returns(toBeReturned)); }