private static ClusterClient<String> createClusterClient(@Nullable Exception exception) throws Exception { final ClusterClient<String> clusterClient = mock(ClusterClient.class); if (exception != null) { doThrow(exception).when(clusterClient).stop(any(JobID.class)); } return clusterClient; } }
@Test public void websocketNotFoundExceptionNoMessageBlock() throws Exception { String className = FILTER_CHAIN_PROXY_CLASSNAME; spy(ClassUtils.class); doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(Message.class.getName()), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no websocket block } }
@Test public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception { String className = "javax.servlet.Filter"; spy(ClassUtils.class); doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no http block }
@Test public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception { String className = FILTER_CHAIN_PROXY_CLASSNAME; spy(ClassUtils.class); doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no http block }
/** * This test exists to prevent any possible regression and let of * https://github.com/checkstyle/checkstyle/issues/1192 to be persistent * event is not very obvious. * * @throws Exception when smth is not expected */ @Test public void testIsLoadableWithNoClassDefFoundError() throws Exception { final Set<String> imports = new HashSet<>(); imports.add("java.applet.someClass"); final ClassResolver classResolver = PowerMockito.spy(new ClassResolver(Thread .currentThread().getContextClassLoader(), "", imports)); PowerMockito.doThrow(new NoClassDefFoundError("expected exception")) .when(classResolver, "safeLoad", any()); final boolean result = classResolver.isLoadable("someClass"); assertFalse("result should be false", result); }
@Test public void testLogInThrowsIfCannotStartFacebookActivity() { doThrow(new ActivityNotFoundException()).when(mockActivity) .startActivityForResult(any(Intent.class), anyInt()); LoginManager loginManager = new LoginManager(); try { loginManager.logInWithReadPermissions(mockActivity, Arrays.asList("public_profile", "user_friends")); fail(); } catch(FacebookException exception) { } }
@Test public void filterChainProxyClassNotFoundException() throws Exception { String className = FILTER_CHAIN_PROXY_CLASSNAME; thrown.expect(BeanDefinitionParsingException.class); thrown.expectMessage("ClassNotFoundException: " + className); spy(ClassUtils.class); doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK); }
@Test public void filterNoClassDefFoundError() throws Exception { String className = "javax.servlet.Filter"; thrown.expect(BeanDefinitionParsingException.class); thrown.expectMessage("NoClassDefFoundError: " + className); spy(ClassUtils.class); doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK); }
@Test public void testIoExceptionWhenLoadingHeaderFile() throws Exception { final HeaderCheck check = PowerMockito.spy(new HeaderCheck()); PowerMockito.doThrow(new IOException("expected exception")).when(check, "loadHeader", any()); check.setHeaderFile(CommonUtil.getUriByFilename(getPath("InputHeaderRegexp.java"))); final Method loadHeaderFile = AbstractHeaderCheck.class.getDeclaredMethod("loadHeaderFile"); loadHeaderFile.setAccessible(true); try { loadHeaderFile.invoke(check); fail("Exception expected"); } catch (InvocationTargetException ex) { assertTrue("Invalid exception cause", ex.getCause() instanceof CheckstyleException); assertTrue("Invalid exception cause message", ex.getCause().getMessage().startsWith("unable to load header file ")); } }
@Test public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception { String className = "javax.servlet.Filter"; spy(ClassUtils.class); doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); Log logger = mock(Log.class); SecurityNamespaceHandler handler = new SecurityNamespaceHandler(); ReflectionTestUtils.setField(handler, "logger", logger); handler.init(); verifyStatic(ClassUtils.class); ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); verifyZeroInteractions(logger); }
@Test public void testResolveQualifiedNameFails() throws Exception { final Set<String> imports = new HashSet<>(); imports.add("java.applet.someClass"); final ClassResolver classResolver = PowerMockito.spy(new ClassResolver(Thread .currentThread().getContextClassLoader(), "", imports)); PowerMockito.doThrow(new ClassNotFoundException("expected exception")) .when(classResolver, "safeLoad", any()); PowerMockito.doReturn(true).when(classResolver, "isLoadable", any()); try { classResolver.resolve("someClass", ""); fail("IllegalStateException is expected"); } catch (IllegalStateException ex) { // exception is expected final String expected = "expected exception"; assertTrue("Invalid exception cause, should be: ClassNotFoundException", ex.getCause() instanceof ClassNotFoundException); assertTrue("Invalid exception message, should end with: " + expected, ex.getMessage().endsWith(expected)); } }
@Test public void testIoExceptionWhenLoadingHeader() throws Exception { final HeaderCheck check = PowerMockito.spy(new HeaderCheck()); PowerMockito.doThrow(new IOException("expected exception")).when(check, "loadHeader", any()); try { check.setHeader("header"); fail("Exception expected"); } catch (IllegalArgumentException ex) { assertTrue("Invalid exception cause", ex.getCause() instanceof IOException); assertEquals("Invalid exception message", "unable to load header", ex.getMessage()); } }
doThrow(new IOException("mock exception")).when(ModuleReflectionUtil.class); ModuleReflectionUtil.getCheckstyleModules(packages, classLoader);
@Test(expected = AdVpnThread.VpnNetworkException.class) public void testSendPacket_error() throws Exception { doThrow(new IOException("Cannot send")).when(mockSocket).send(any(DatagramPacket.class)); watchdog.lastPacketSent = 0; watchdog.sendPacket(); }
@Test public void ignoresErrorsWhileRemovingArtifactDataFolder() throws Exception { AbstractDeployableArtifactFactory artifactFactory = mock(AbstractDeployableArtifactFactory.class); ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class); DefaultArchiveDeployer<Application> deployer = new DefaultArchiveDeployer(artifactDeployer, artifactFactory, new ObservableList(), null, null); deployer.setDeploymentListener(mock(DeploymentListener.class)); deployer.deployArtifact(createMockApplication(), empty()); mockStatic(FileUtils.class); PowerMockito.doThrow(new IOException()).when(FileUtils.class); deleteDirectory(Matchers.eq(getAppDataFolder(ARTIFACT_ID))); deployer.undeployArtifact(ARTIFACT_ID); }
@Test public void testFinishWrite_closeFailure() throws Exception { doCallRealMethod().when(reader).finishWrite(any(FileOutputStream.class)); doNothing().when(reader).failWrite(any(FileOutputStream.class)); doThrow(new IOException("Not closing")).when(fos).close(); when(workFile.renameTo(activeFile)).thenReturn(true); try { reader.finishWrite(fos); Mockito.verify(fos).close(); Mockito.verify(reader).failWrite(fos); fail("Failing close should fail finish"); } catch (IOException e) { assertTrue(e.getMessage() + "wrong", e.getMessage().contains("Not closing")); } }
@Test public void testDownloadFile_exception() throws Exception { RuleDatabaseItemUpdateRunnable itemUpdateRunnable = new RuleDatabaseItemUpdateRunnable(realTask, mockContext, mock(Configuration.Item.class)); FileOutputStream fos = mock(FileOutputStream.class); InputStream is = mock(InputStream.class); when(connection.getInputStream()).thenReturn(is); when(singleWriterMultipleReaderFile.startWrite()).thenReturn(fos); doThrow(new IOException("foobar")).when(fos, "write", any(byte[].class), anyInt(), anyInt()); try { itemUpdateRunnable.downloadFile(file, singleWriterMultipleReaderFile, connection); fail("Should have thrown exception"); } catch (IOException e) { assertEquals("foobar", e.getMessage()); assertEquals(1, failAnswer.numCalls); assertEquals(0, finishAnswer.numCalls); } }
@Test @PrepareForTest({Log.class, Os.class}) public void testCloseOrWarn_fileDescriptor() throws Exception { FileDescriptor fd = mock(FileDescriptor.class); mockStatic(Log.class); mockStatic(Os.class); when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null)); // Closing null should work just fine testResult = 0; assertNull(FileHelper.closeOrWarn((FileDescriptor) null, "tag", "msg")); assertEquals(0, testResult); // Successfully closing the file should not log. testResult = 0; assertNull(FileHelper.closeOrWarn(fd, "tag", "msg")); assertEquals(0, testResult); // If closing fails, it should log. testResult = 0; doThrow(new ErrnoException("close", 0)).when(Os.class, "close", any(FileDescriptor.class)); assertNull(FileHelper.closeOrWarn(fd, "tag", "msg")); assertEquals(1, testResult); }
private DBOpenHelper mockUnencryptedDB() { DBOpenHelper dbOpenHelper = spy(new DBOpenHelper(null)); doThrow(new SQLiteException()).when(dbOpenHelper).getWritableDatabase(argThat(CoreMatchers.not(CoreMatchers.equalTo("")))); doReturn(sqLiteDatabase).when(dbOpenHelper).getWritableDatabase(""); return dbOpenHelper; }