@Test public void shouldThrowExceptionIfUrlIsInvalid() throws Exception { ServerUrlGenerator serverUrlGenerator = mock(ServerUrlGenerator.class); when(serverUrlGenerator.serverUrlFor("admin/agent")).thenReturn("invalidUrl"); exception.expect(RuntimeException.class); exception.expectMessage("URL you provided to access Go Server: " + "invalidUrl" + " is not valid"); DownloadableFile.AGENT.validatedUrl(serverUrlGenerator); } }
@Test public void shouldFailOnRSA384SigningWhenProvidedPrivateKeyIsNull() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: SHA384withRSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Private Key is null."))); RSAKeyProvider provider = mock(RSAKeyProvider.class); when(provider.getPrivateKey()).thenReturn(null); Algorithm algorithm = Algorithm.RSA384(provider); algorithm.sign(new byte[0], new byte[0]); }
private void expectContainerMissingValueAttribute() { exception.expect(AnnotationConfigurationException.class); exception.expectMessage(startsWith("Invalid declaration of container type")); exception.expectMessage(containsString(ContainerMissingValueAttribute.class.getName())); exception.expectMessage(containsString("for repeatable annotation")); exception.expectMessage(containsString(InvalidRepeatable.class.getName())); exception.expectCause(isA(NoSuchMethodException.class)); }
@Test public void loadIndexWithException() throws IOException { final IOException cause = new IOException("test exception"); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Unable to load indexes"); this.thrown.expectCause(is(cause)); CandidateComponentsIndexLoader.loadIndex(new CandidateComponentsTestClassLoader( getClass().getClassLoader(), cause)); }
@Test public void invokeListenerRuntimeException() { Method method = ReflectionUtils.findMethod( SampleEvents.class, "generateRuntimeException", GenericTestEvent.class); GenericTestEvent<String> event = createGenericTestEvent("fail"); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Test exception"); this.thrown.expectCause(is((Throwable) isNull())); invokeListener(method, event); }
@Test public void closeAllAndRethrowException() throws Exception { doThrow( new IOException( "Faulty closable" ) ).when( faultyClosable ).close(); expectedException.expect( IOException.class ); expectedException.expectMessage( "Exception closing multiple resources" ); expectedException.expect( new NestedThrowableMatcher( IOException.class ) ); IOUtils.closeAll( goodClosable1, faultyClosable, goodClosable2 ); }
@Test public void does_not_authenticate_from_user_token_when_token_does_not_match_existing_user() { when(userTokenAuthentication.authenticate("token")).thenReturn(Optional.of("Unknown user")); when(request.getHeader("Authorization")).thenReturn("Basic " + toBase64("token:")); expectedException.expect(authenticationException().from(Source.local(Method.BASIC_TOKEN)).withoutLogin().andNoPublicMessage()); try { underTest.authenticate(request); } finally { verifyZeroInteractions(authenticationEvent); } }
@Test public void getDynamicForkJoinTasksAndInputException() { //Given WorkflowTask dynamicForkJoinToSchedule = new WorkflowTask(); dynamicForkJoinToSchedule.setType(TaskType.FORK_JOIN_DYNAMIC.name()); dynamicForkJoinToSchedule.setTaskReferenceName("dynamicfanouttask"); dynamicForkJoinToSchedule.setDynamicForkJoinTasksParam("dynamicTasks"); dynamicForkJoinToSchedule.getInputParameters().put("dynamicTasks", "dt1.output.dynamicTasks"); dynamicForkJoinToSchedule.getInputParameters().put("dynamicTasksInput", "dt1.output.dynamicTasksInput"); DynamicForkJoinTaskList dtasks = new DynamicForkJoinTaskList(); Map<String, Object> input = new HashMap<>(); input.put("k1", "v1"); dtasks.add("junit_task_2", null, "xdt1", input); HashMap<String, Object> input2 = new HashMap<>(); input2.put("k2", "v2"); dtasks.add("junit_task_3", null, "xdt2", input2); Map<String, Object> dynamicTasksInput = new HashMap<>(); dynamicTasksInput.put("dynamicTasks", dtasks); //when when(parametersUtils.getTaskInput(anyMap(), any(Workflow.class), any(TaskDef.class), anyString())) .thenReturn(dynamicTasksInput); when(objectMapper.convertValue(anyObject(),any(Class.class))).thenReturn(null); //then expectedException.expect(TerminateWorkflowException.class); forkJoinDynamicTaskMapper.getDynamicForkJoinTasksAndInput(dynamicForkJoinToSchedule, new Workflow()); }
@Test public void testFailuresSuppressed() throws IOException { Writer mockWriter = Mockito.mock(Writer.class); doThrow(new IOException("Error appending")).when(mockWriter).append(any()); doThrow(new IOException("Error closing")).when(mockWriter).close(); when(sourceFile.openWriter()).thenReturn(mockWriter); thrown.expect(IOException.class); thrown.expectMessage("Error appending"); thrown.expect(suppressed(instanceOf(IOException.class))); thrown.expect(suppressed(hasProperty("message", equalTo("Error closing")))); FilerUtils.writeCompilationUnit(filer, unit, originatingElement); }
@Test public void throws_ISE_if_handler_fails() throws Exception { Oracle dialect = new Oracle(); when(underTest.getHandler(dialect)).thenReturn(handler); when(db.getDialect()).thenReturn(dialect); doThrow(new SQLException("failure")).when(handler).handle(any(Connection.class), any(DatabaseCharsetChecker.State.class)); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("failure"); underTest.check(DatabaseCharsetChecker.State.UPGRADE); }
@Test public void testCloseError() throws IOException { Reader reader = mock(Reader.class); when(reader.read(any(char[].class), anyInt(), anyInt())).thenReturn(-1); doThrow(new IOException()).when(reader).close(); WsTestUtil.mockReader(wsClient, reader); exception.expect(IllegalStateException.class); metricsRepositoryLoader.load(); } }
@Test public void shouldFailOnUnreadableRessources() throws IOException { this.thrown.expect(PitError.class); when(this.byteSource.getBytes(anyString())).thenReturn( Optional.<byte[]> empty()); this.testee.getJarLocation(); }
@Test public void shouldThrowAnExceptionIfScmViewReturnedByPluginIsNull() { GoPluginDescriptor descriptor = new GoPluginDescriptor("plugin1", null, null, null, null, false); when(extension.getSCMView("plugin1")).thenReturn(null); thrown.expectMessage("Plugin[plugin1] returned null scm view"); new SCMPluginInfoBuilder(extension).pluginInfoFor(descriptor); } }
@Test public void testWindowStateNotAvailableToMergingWindows() throws Exception { WindowAssigner<Integer, TimeWindow> mockAssigner = mockMergingAssigner(); Trigger<Integer, TimeWindow> mockTrigger = mockTrigger(); InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction = mockWindowFunction(); KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness = createWindowOperator(mockAssigner, mockTrigger, 20L, mockWindowFunction); testHarness.open(); when(mockTrigger.onElement(anyInt(), anyLong(), anyTimeWindow(), anyTriggerContext())) .thenReturn(TriggerResult.FIRE); when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext())) .thenReturn(Arrays.asList(new TimeWindow(0, 20))); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { InternalWindowFunction.InternalWindowContext context = (InternalWindowFunction.InternalWindowContext) invocationOnMock.getArguments()[2]; context.windowState().getState(valueStateDescriptor).update("hello"); return null; } }).when(mockWindowFunction).process(anyInt(), anyTimeWindow(), anyInternalWindowContext(), anyIntIterable(), WindowOperatorContractTest.<Void>anyCollector()); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Per-window state is not allowed when using merging windows."); testHarness.processElement(new StreamRecord<>(0, 0L)); }
@Test public void sendWithExecutionException() { this.session.afterConnected(this.connection); assertTrue(this.session.isConnected()); IllegalStateException exception = new IllegalStateException("simulated exception"); SettableListenableFuture<Void> future = new SettableListenableFuture<>(); future.setException(exception); when(this.connection.send(any())).thenReturn(future); this.expected.expect(MessageDeliveryException.class); this.expected.expectCause(Matchers.sameInstance(exception)); this.session.send("/topic/foo", "sample payload".getBytes(StandardCharsets.UTF_8)); verifyNoMoreInteractions(this.connection); }
@Test public void testWorkflowDeleteThrowException() { MetadataClient mockClient = Mockito.mock(MetadataClient.class); expectedException.expect(RuntimeException.class); expectedException.expectMessage("Invalid Workflow name"); doThrow(new RuntimeException("Invalid Workflow name")).when(mockClient).unregisterWorkflowDef(anyString(), any()); mockClient.unregisterWorkflowDef("hello", 1); }
@Test public void addPropertiesFilesToEnvironmentWithContextAndNullLocations() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("must not be null"); addPropertiesFilesToEnvironment(mock(ConfigurableApplicationContext.class), (String[]) null); }
@Test public void testReadRetryEventuallyGivesUp() throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1); when(gcsChannel.read(eq(buffer))) .thenThrow( new StorageException( new IOException( "Connection closed prematurely: bytesRead = 33554432, Content-Length = 41943040"))) .thenThrow( new StorageException( new IOException( "Connection closed prematurely: bytesRead = 33554432, Content-Length = 41943040"))) .thenReturn(1); assertThat(chan.position()).isEqualTo(0L); thrown.expect(StorageException.class); chan.read(buffer); }
@Test public void testFetchNextRecordReaderThrowsException() throws Exception { DummyRecordReader recordReader = mock(DummyRecordReader.class); when(recordReader.nextKeyValue()).thenThrow(new InterruptedException()); HadoopInputFormat<String, Long> hadoopInputFormat = setupHadoopInputFormat(new DummyInputFormat(), Job.getInstance(), recordReader); exception.expect(IOException.class); hadoopInputFormat.fetchNext(); assertThat(hadoopInputFormat.hasNext, is(true)); }