@Test @PrepareForTest({Converter.class, QppOutputEncoder.class}) public void testEncodingExceptions() throws Exception { QppOutputEncoder encoder = mock(QppOutputEncoder.class); whenNew(QppOutputEncoder.class).withAnyArguments().thenReturn(encoder); EncodeException ex = new EncodeException("mocked", new RuntimeException()); doThrow(ex).when(encoder).encode(); Path path = Paths.get("src/test/resources/converter/defaultedNode.xml"); Converter converter = new Converter(new PathSource(path)); converter.getContext().setDoDefaults(false); converter.getContext().setDoValidation(false); try { converter.transform(); fail(); } catch (TransformException exception) { checkup(exception, ErrorCode.NOT_VALID_XML_DOCUMENT); } }
@Test @PrepareForTest({Converter.class, XmlUtils.class}) public void testUnexpectedError() { mockStatic(XmlUtils.class); when(XmlUtils.fileToStream(any(Path.class))).thenReturn(null); Path path = Paths.get("../qrda-files/valid-QRDA-III.xml"); Converter converter = new Converter(new PathSource(path)); try { converter.transform(); fail(); } catch (TransformException exception) { checkup(exception, ErrorCode.UNEXPECTED_ERROR); } }
@PrepareForTest({ ScriptBuilder.class }) @Test public void redeemScript() { final List<Integer> calls = new ArrayList<>(); PowerMockito.mockStatic(ScriptBuilder.class); PowerMockito.when(ScriptBuilder.createRedeemScript(any(int.class), any(List.class))).thenAnswer((invocationOnMock) -> { calls.add(1); int numberOfSignaturesRequired = invocationOnMock.getArgumentAt(0, int.class); List<BtcECKey> publicKeys = invocationOnMock.getArgumentAt(1, List.class); Assert.assertEquals(4, numberOfSignaturesRequired); Assert.assertEquals(6, publicKeys.size()); for (int i = 0; i < sortedPublicKeys.size(); i++) { Assert.assertTrue(Arrays.equals(sortedPublicKeys.get(i).getPubKey(), publicKeys.get(i).getPubKey())); } return new Script(new byte[]{(byte)0xaa}); }); Assert.assertTrue(Arrays.equals(federation.getRedeemScript().getProgram(), new byte[]{(byte) 0xaa})); Assert.assertTrue(Arrays.equals(federation.getRedeemScript().getProgram(), new byte[]{(byte) 0xaa})); // Make sure the script creation happens only once Assert.assertEquals(1, calls.size()); }
@PrepareForTest({ ScriptBuilder.class }) @Test public void P2SHScript() { final List<Integer> calls = new ArrayList<>(); PowerMockito.mockStatic(ScriptBuilder.class); PowerMockito.when(ScriptBuilder.createP2SHOutputScript(any(int.class), any(List.class))).thenAnswer((invocationOnMock) -> { calls.add(0); int numberOfSignaturesRequired = invocationOnMock.getArgumentAt(0, int.class); List<BtcECKey> publicKeys = invocationOnMock.getArgumentAt(1, List.class); Assert.assertEquals(4, numberOfSignaturesRequired); Assert.assertEquals(6, publicKeys.size()); for (int i = 0; i < sortedPublicKeys.size();i ++) { Assert.assertTrue(Arrays.equals(sortedPublicKeys.get(i).getPubKey(), publicKeys.get(i).getPubKey())); } return new Script(new byte[]{(byte)0xaa}); }); Assert.assertTrue(Arrays.equals(federation.getP2SHScript().getProgram(), new byte[]{(byte) 0xaa})); Assert.assertTrue(Arrays.equals(federation.getP2SHScript().getProgram(), new byte[]{(byte) 0xaa})); // Make sure the script creation happens only once Assert.assertEquals(1, calls.size()); }
@PrepareForTest({ ScriptBuilder.class }) @Test public void Address() { // Since we can't mock both Address and ScriptBuilder at the same time (due to PowerMockito limitations) // we use a well known P2SH and its corresponding address // and just mock the ScriptBuilder // a914896ed9f3446d51b5510f7f0b6ef81b2bde55140e87 => 2N5muMepJizJE1gR7FbHJU6CD18V3BpNF9p final List<Integer> calls = new ArrayList<>(); PowerMockito.mockStatic(ScriptBuilder.class); PowerMockito.when(ScriptBuilder.createP2SHOutputScript(any(int.class), any(List.class))).thenAnswer((invocationOnMock) -> { calls.add(0); int numberOfSignaturesRequired = invocationOnMock.getArgumentAt(0, int.class); List<BtcECKey> publicKeys = invocationOnMock.getArgumentAt(1, List.class); Assert.assertEquals(4, numberOfSignaturesRequired); Assert.assertEquals(6, publicKeys.size()); for (int i = 0; i < sortedPublicKeys.size();i ++) { Assert.assertTrue(Arrays.equals(sortedPublicKeys.get(i).getPubKey(), publicKeys.get(i).getPubKey())); } return new Script(Hex.decode("a914896ed9f3446d51b5510f7f0b6ef81b2bde55140e87")); }); Assert.assertEquals("2N5muMepJizJE1gR7FbHJU6CD18V3BpNF9p", federation.getAddress().toBase58()); Assert.assertEquals("2N5muMepJizJE1gR7FbHJU6CD18V3BpNF9p", federation.getAddress().toBase58()); // Make sure the address creation happens only once Assert.assertEquals(1, calls.size()); }
@Test @PrepareForTest({Environment.class}) public void testGetItemFile() throws Exception { File file = new File("/dir/"); when(mockContext.getExternalFilesDir(null)).thenReturn(file); Configuration.Item item = new Configuration.Item(); item.location = "http://example.com/"; assertEquals(new File("/dir/http%3A%2F%2Fexample.com%2F"), FileHelper.getItemFile(mockContext, item)); item.location = "https://example.com/"; assertEquals(new File("/dir/https%3A%2F%2Fexample.com%2F"), FileHelper.getItemFile(mockContext, item)); item.location = "file:/myfile"; assertNull(FileHelper.getItemFile(mockContext, item)); mockStatic(Environment.class); when(Environment.getExternalStorageDirectory()).thenReturn(new File("/sdcard/")); item.location = "file:myfile"; assertNull(null, FileHelper.getItemFile(mockContext, item)); item.location = "ahost.com"; assertNull(FileHelper.getItemFile(mockContext, item)); }
@Test @PrepareForTest({Log.class, Os.class}) public void testPoll_retryInterrupt() throws Exception { mockStatic(Log.class); mockStatic(Os.class); when(Os.poll(any(StructPollfd[].class), anyInt())).then(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { // First try fails with EINTR, seconds returns success. if (testResult++ == 0) { // Android actually sets all OsConstants to 0 when running the // unit tests, so this works, but another constant would have // exactly the same result. throw new ErrnoException("poll", OsConstants.EINTR); } return 0; } }); // poll() will be interrupted first time, so called a second time. assertEquals(0, FileHelper.poll(null, 0)); assertEquals(2, testResult); }
@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); }
@Test @PrepareForTest(Log.class) public void testCloseOrWarn_closeable() throws Exception { Closeable closeable = mock(Closeable.class); mockStatic(Log.class); when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null)); // Closing null should work just fine testResult = 0; assertNull(FileHelper.closeOrWarn((Closeable) null, "tag", "msg")); assertEquals(0, testResult); // Successfully closing the file should not log. testResult = 0; assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg")); assertEquals(0, testResult); // If closing fails, it should log. when(closeable).thenThrow(new IOException("Foobar")); testResult = 0; assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg")); assertEquals(1, testResult); }
@PrepareForTest({Log.class, FileHelper.class}) public void testInitialize_disabled() throws Exception { RuleDatabase ruleDatabase = spy(new RuleDatabase()); Configuration.Item item = new Configuration.Item(); item.location = "ahost.com"; item.state = Configuration.Item.STATE_DENY; Configuration configuration = new Configuration(); configuration.hosts = new Configuration.Hosts(); configuration.hosts.enabled = false; configuration.hosts.items = new ArrayList<>(); configuration.hosts.items.add(item); Context context = mock(Context.class); mockStatic(FileHelper.class); when(FileHelper.loadCurrentSettings(context)).thenReturn(configuration); when(FileHelper.openItemFile(context, item)).thenReturn(null); ruleDatabase.initialize(context); assertFalse(ruleDatabase.isBlocked("ahost.com")); assertTrue(ruleDatabase.isEmpty()); }
@Test @PrepareForTest({Log.class, FileHelper.class}) public void testInitialize_fileNotFound() throws Exception { RuleDatabase ruleDatabase = spy(new RuleDatabase()); Configuration.Item item = new Configuration.Item(); item.location = "protocol://some-weird-file-uri"; item.state = Configuration.Item.STATE_DENY; Configuration configuration = new Configuration(); configuration.hosts = new Configuration.Hosts(); configuration.hosts.enabled = true; configuration.hosts.items = new ArrayList<>(); configuration.hosts.items.add(item); Context context = mock(Context.class); mockStatic(FileHelper.class); when(FileHelper.loadCurrentSettings(context)).thenReturn(configuration); when(FileHelper.openItemFile(context, item)).thenThrow(new FileNotFoundException("foobar")); ruleDatabase.initialize(context); assertTrue(ruleDatabase.isEmpty()); }
@Test @PrepareForTest(SystemDirectory.class) public void testGetArtifactRootDir() throws Exception { final File file = new File("bamboo-artifacts/"); final ArtifactStorage storage = PowerMockito.mock(ArtifactStorage.class); PowerMockito.mockStatic(SystemDirectory.class); PowerMockito.when(SystemDirectory.getArtifactStorage()).thenReturn(storage); final PlanResultKey key = createResultKey(); final ArtifactDefinitionContext artifact = createArtifact(); PowerMockito.when(storage.getArtifactDirectory(key)).thenReturn(file); final BambooFileStorageHelper storageHelper = new BambooFileStorageHelper(); storageHelper.setResultKey(key); storageHelper.setArtifactDefinition(artifact); final File reportFile = storageHelper.buildArtifactRootDirectory(); final String path = file.getCanonicalPath() + "/Hub_Risk_Report"; final String reportFilePath = reportFile.getCanonicalPath(); assertEquals(key, storageHelper.getResultKey()); assertEquals(artifact, storageHelper.getArtifactDefinition()); assertEquals(path, reportFilePath); }
@Test @PrepareForTest(value = {Utils.class}) public void testMainJarCopied() throws Exception { prepareJetBuildDir(); mockCopying("copyFile"); File mainJarSpy = Tests.fileSpy(Tests.mainJar); ExcelsiorJet excelsiorJet = Tests.excelsiorJet(); JetProject prj = Mockito.spy(Tests.testProject(ApplicationType.PLAIN). mainJar(mainJarSpy)); prj.processDependencies(); Mockito.doNothing().when(prj).validate(excelsiorJet, true); Mockito.when(excelsiorJet.compile(Tests.jetBuildDir.toFile(), "=p", "test.prj", "-jetvmprop=")).thenReturn(0); JetBuildTask buildTask = Mockito.spy(new JetBuildTask(excelsiorJet, prj, false)); buildTask.execute(); Mockito.verify(excelsiorJet).compile(Tests.jetBuildDir.toFile(), "=p", "test.prj", "-jetvmprop="); Path from = fromCaptor.getValue(); Path to = toCaptor.getValue(); assertEquals(Tests.mainJar.toString(), from.toFile().getAbsolutePath()); assertEquals(Tests.jetBuildDir.resolve("test.jar").toString(), to.toFile().getAbsolutePath()); }
@Test @PrepareForTest(value = {Utils.class}) public void testExternalJarCopied() throws Exception { mockCopying("copyFile"); ExcelsiorJet excelsiorJet = Tests.excelsiorJet(); File externalJar = Tests.fileSpy(Tests.externalJarAbs); File mainJarSpy = Tests.fileSpy(Tests.mainJar); JetProject prj = Mockito.spy(Tests.testProject(ApplicationType.PLAIN). dependencies(singletonList(DependencyBuilder.testExternalDependency(externalJar).pack(ClasspathEntry.PackType.ALL).asDependencySettings())). mainJar(mainJarSpy)); prj.processDependencies(); Mockito.doNothing().when(prj).validate(excelsiorJet, true); Mockito.when(excelsiorJet.compile(null, "=p", "test.prj", "-jetvmprop=")).thenReturn(0); JetBuildTask buildTask = new JetBuildTask(excelsiorJet, prj, false); buildTask.execute(); Mockito.verify(excelsiorJet).compile(Tests.jetBuildDir.toFile(), "=p", "test.prj", "-jetvmprop="); Path externalFrom = fromCaptor.getAllValues().get(1); Path externalTo = toCaptor.getAllValues().get(1); assertEquals(Tests.externalJarAbs.toString(), externalFrom.toFile().getAbsolutePath()); assertEquals(Tests.jetBuildDir.resolve(Tests.externalJarRel).toString(), externalTo.toFile().getAbsolutePath()); }
@Test @PrepareForTest(value = {Utils.class}) public void testMainJarNotCopiedForTomcatApp() throws Exception { prepareJetBuildDir(); mockUtilsClass(); ExcelsiorJet excelsiorJet = Tests.excelsiorJet(); JetProject prj = Mockito.spy(Tests.testProject(ApplicationType.TOMCAT)); prj.processDependencies(); prj.tomcatConfiguration().tomcatHome = "/tomcat-home"; Mockito.doNothing().when(prj).validate(excelsiorJet, true); Mockito.when(excelsiorJet.compile(null, "=p", "test.prj", "-jetvmprop=")).thenReturn(0); JetBuildTask buildTask = new JetBuildTask(excelsiorJet, prj, false); buildTask.execute(); PowerMockito.verifyStatic(Mockito.never()); Utils.copy(anyObject(), anyObject()); }
@Test @PrepareForTest(value = {Utils.class}) public void testExternalDisabledJarCopiedToLib() throws Exception { mockCopying("copyFile"); ExcelsiorJet excelsiorJet = Tests.excelsiorJet(); File externalJar = Tests.fileSpy(Tests.externalJarAbs); DependencySettings dep = DependencyBuilder.testExternalDependency(externalJar).pack(ClasspathEntry.PackType.NONE).disableCopyToPackage(true).asDependencySettings(); JetProject prj = Mockito.spy(Tests.testProject(ApplicationType.PLAIN). mainJar(Tests.fileSpy(Tests.mainJar)). dependencies(singletonList(dep))); prj.processDependencies(); Mockito.doNothing().when(prj).validate(excelsiorJet, true); Mockito.when(excelsiorJet.compile(null, "=p", "test.prj", "-jetvmprop=")).thenReturn(0); JetBuildTask buildTask = new JetBuildTask(excelsiorJet, prj, false); buildTask.execute(); Mockito.verify(excelsiorJet).compile(Tests.jetBuildDir.toFile(), "=p", "test.prj", "-jetvmprop="); Path externalFrom = fromCaptor.getAllValues().get(1); Path externalTo = toCaptor.getAllValues().get(1); assertEquals(Tests.externalJarAbs, externalFrom); assertEquals(Tests.jetBuildDir.resolve(Tests.externalJarRel), externalTo); }
@Test @PrepareForTest({ CommonUtils.class, CommonUtilsTest.class }) @SuppressWarnings("unchecked") public void testLoadSuppressionsUriSyntaxException() throws Exception { final URL configUrl = mock(URL.class); when(configUrl.toURI()).thenThrow(URISyntaxException.class); mockStatic(CommonUtils.class, Mockito.CALLS_REAL_METHODS); final String fileName = "suppressions_none.xml"; when(CommonUtils.class.getResource(fileName)).thenReturn(configUrl); try { CommonUtils.getUriByFilename(fileName); fail("Exception is expected"); } catch (CheckstyleException ex) { assertTrue("Invalid exception cause", ex.getCause() instanceof URISyntaxException); assertEquals("Invalid exception message", "Unable to find: " + fileName, ex.getMessage()); } }
@Test @PrepareForTest({FilterUtils.class, CommonUtils.class}) public void testExceptionOnClosing() throws Exception { final File file = temporaryFolder.newFile("existing.xml"); final InputStream inputStream = PowerMockito.mock(InputStream.class); Mockito.doThrow(IOException.class).when(inputStream).close(); final URL url = PowerMockito.mock(URL.class); BDDMockito.given(url.openStream()).willReturn(inputStream); final URI uri = PowerMockito.mock(URI.class); BDDMockito.given(uri.toURL()).willReturn(url); PowerMockito.mockStatic(CommonUtils.class); final String fileName = file.getPath(); BDDMockito.given(CommonUtils.getUriByFilename(fileName)).willReturn(uri); assertFalse("Should be false, because error on close", FilterUtils.isFileExists(fileName)); }
@Test @PrepareForTest(ParseMode.class) public void testOpenFileWithUnknownParseMode() throws CheckstyleException { final ParseMode unknownParseMode = PowerMockito.mock(ParseMode.class); Whitebox.setInternalState(unknownParseMode, "ordinal", 3); PowerMockito.when(unknownParseMode.toString()).thenReturn("Unknown parse mode"); PowerMockito.mockStatic(ParseMode.class); PowerMockito.when(ParseMode.values()).thenReturn( new ParseMode[] { ParseMode.PLAIN_JAVA, ParseMode.JAVA_WITH_COMMENTS, ParseMode.JAVA_WITH_JAVADOC_AND_COMMENTS, unknownParseMode, }); try { model.setParseMode(unknownParseMode); model.openFile(testData); fail("Expected IllegalArgumentException is not thrown."); } catch (IllegalArgumentException ex) { assertEquals("Invalid exception message", "Unknown mode: Unknown parse mode", ex.getMessage()); } }
@SuppressWarnings( "unused" ) @PrepareForTest( { FitNesseHelper.class } ) @Test public void forkFitNesseServer_launcherInSeparateProcess() throws Exception { String javaHome = System.getProperty("java.home"); String javaClassPath = System.getProperty( "java.class.path" ); PowerMockito.mockStatic( System.class ); PowerMockito.when( System.getProperty( "java.home" ) ).thenReturn( javaHome ); PowerMockito.when( System.getProperty( AbstractFitNesseMojo.MAVEN_CLASSPATH ) ).thenReturn( currentClassPath() ); File logDir = new File( System.getProperty( "java.io.tmpdir" ), "fitnesse-launcher-logs" ); String port = String.valueOf( DEFAULT_COMMAND_PORT ); File working = new File( System.getProperty( "java.io.tmpdir" ), "fitnesse-launcher-test" ); Process fitnesseProcess = fitNesseHelper.forkFitNesseServer( port, working.getCanonicalPath(), FitNesseHelper.DEFAULT_ROOT, logDir.getCanonicalPath(), javaClassPath ); // TEAR DOWN: fitNesseHelper.shutdownFitNesseServer( port, null ); //fitnesseProcess.destroy(); }
/** * Test convert document to byte array. * * @throws Exception * If something unexpected goes wrong. */ @Test @PrepareForTest @SuppressStaticInitializationFor public void testConvertDocumentToByteArray() throws Exception { // Create a fake document. Document document = DocumentHelper.createDocument(); Element root = document.addElement("ListExecutionContexts"); root.addAttribute("id", "2"); replayAll(); // Perform the test final byte[] array = tested.convertDocumentToByteArray(document); verifyAll(); assertNotNull(array); assertEquals(70, array.length); }
/** * Checks if the node state changes to COMPLETE when the network interface * configuration is done. */ @PrepareForTest(RemoteIpCommandUtil.class) @Test public void testProcessPortCreatedState() { Session mockSession = createMock(Session.class); mockStatic(RemoteIpCommandUtil.class); expect(connect(anyObject())).andReturn(mockSession); expect(getCurrentIps(mockSession, INTEGRATION_BRIDGE)).andReturn(Sets.newHashSet(TEST_CIDR_ADDR.ip())); expect(getCurrentIps(mockSession, TEST_DATA_IFACE)).andReturn(Sets.newHashSet()); expect(isInterfaceUp(anyObject(), anyObject())).andReturn(true).anyTimes(); RemoteIpCommandUtil.disconnect(anyObject()); PowerMock.replay(RemoteIpCommandUtil.class); // There's no events for IP address changes on the interfaces, so just // Set node state updated to trigger node bootstrap nodeManager.updateNodeAndMakeEvent(NODE_3); CordVtnNode current = nodeManager.node(NODE_3.integrationBridgeId()); assertEquals(ERR_STATE, COMPLETE, current.state()); }
/** * Checks if the node state falls back to PORT_CREATED when the interface * configurations are incomplete. */ @PrepareForTest(RemoteIpCommandUtil.class) @Test public void testBackToPortCreatedStateWhenIpRemoved() { // Mocks SSH connection failure mockStatic(RemoteIpCommandUtil.class); expect(connect(anyObject())).andReturn(null); PowerMock.replay(RemoteIpCommandUtil.class); // ONOS is not able to detect IP is removed from the interface // Just triggers node update event for the PORT_CREATED node and // check if it stays in PORT_CREATED state nodeManager.updateNode(NODE_3); CordVtnNode current = nodeManager.node(NODE_3.integrationBridgeId()); assertEquals(ERR_STATE, PORT_CREATED, current.state()); }
@PrepareForTest({Intercom.class}) @Test public void testSendEvent_unTimed_withParams() { PowerMockito.mockStatic(Intercom.class); PowerMockito.when(Intercom.client()).thenReturn(mockedIntercom); AnalyticsEvent event = new AnalyticsEvent("Intercom Event With Params Run") .putAttribute("some_param", "yes") .putAttribute("another_param", "yes again"); provider.sendEvent(event); assertThat(logEventCalled).isTrue(); assertThat(testEventName).isEqualTo("Intercom Event With Params Run"); assertThat(testEventPropertiesMap.keySet()).containsExactlyInAnyOrder("some_param", "another_param"); assertThat(testEventPropertiesMap.values()).containsExactlyInAnyOrder("yes", "yes again"); }
@PrepareForTest({Intercom.class}) @Test public void testLogErrorEvent() { PowerMockito.mockStatic(Intercom.class); PowerMockito.when(Intercom.client()).thenReturn(mockedIntercom); EmptyStackException myException = new EmptyStackException(); ErrorEvent event = new ErrorEvent() .setMessage("something bad happened") .setException(myException); provider.sendEvent(event); assertThat(logEventCalled).isTrue(); assertThat(testEventName).isEqualTo(CommonEvents.ERROR); assertThat(testEventPropertiesMap.keySet()).containsExactlyInAnyOrder("error_message", "exception_object"); assertThat(testEventPropertiesMap.values()).containsExactlyInAnyOrder("something bad happened", myException); }
@PrepareForTest({Intercom.class}) @Test public void test_endTimedEvent_WillThrow() { PowerMockito.mockStatic(Intercom.class); PowerMockito.when(Intercom.client()).thenReturn(mockedIntercom); boolean didThrow = false; AnalyticsEvent event = new AnalyticsEvent("Intercom Timed Event With Parameters") .setTimed(true); try { provider.endTimedEvent(event); // attempting to end a timed event that was not started should throw an exception } catch (IllegalStateException e) { didThrow = true; } assertThat(didThrow).isTrue(); }
@Test @PrepareForTest(WakeOnLanInstallation.class) public void installWakeOnLanTestIfNotInstalled() throws Exception { prepareMockedFileThatRepresentsTheWakeOnLanCommand(false); String command = "aptitude -y install wakeonlan"; final String returnOfInstallationCommand = "return of command"; Mockito.when(wakeOnLanInstallation.shellCommandUtils.executeCommand(command)).thenReturn(returnOfInstallationCommand); wakeOnLanInstallation.installWakeOnLan(); InOrder inOrder = Mockito.inOrder(wakeOnLanInstallation.shellCommandUtils, wakeOnLanInstallation.logger); inOrder.verify(wakeOnLanInstallation.logger).info("Checking if wakeonlan is installed."); inOrder.verify(wakeOnLanInstallation.logger).info("Wakeonlan is not installed."); inOrder.verify(wakeOnLanInstallation.logger).info("Installing wakeonlan."); inOrder.verify(wakeOnLanInstallation.shellCommandUtils).executeCommand(command); inOrder.verify(wakeOnLanInstallation.logger).info(returnOfInstallationCommand); inOrder.verify(wakeOnLanInstallation.logger).info("Installation finished."); Mockito.verify(wakeOnLanInstallation.logger, Mockito.times(0)).info("Wakeonlan is already installed."); }
@Test @PrepareForTest({Converter.class, QrdaValidator.class}) public void testValidationErrors() throws Exception { Context context = new Context(); TestHelper.mockDecoder(context, JennyDecoder.class, new ComponentKey(TemplateId.DEFAULT, Program.ALL)); QrdaValidator mockQrdaValidator = TestHelper.mockValidator(context, TestDefaultValidator.class, new ComponentKey(TemplateId.DEFAULT, Program.ALL), true); PowerMockito.whenNew(QrdaValidator.class) .withAnyArguments() .thenReturn(mockQrdaValidator); Path path = Paths.get("src/test/resources/converter/errantDefaultedNode.xml"); Converter converter = new Converter(new PathSource(path), context); try { converter.transform(); fail("The converter should not create valid QPP JSON"); } catch (TransformException exception) { AllErrors allErrors = exception.getDetails(); List<Error> errors = allErrors.getErrors(); assertWithMessage("There must only be one error source.") .that(errors).hasSize(1); List<Detail> details = errors.get(0).getDetails(); assertWithMessage("The expected validation error was missing") .that(details) .comparingElementsUsing(DetailsErrorEquals.INSTANCE) .contains(new FormattedErrorCode(ErrorCode.UNEXPECTED_ERROR, "Test validation error for Jenny")); } }
@Test @PrepareForTest({Files.class, ConversionFileWriterWrapper.class}) public void testFailureToWriteQpp() throws IOException { PowerMockito.mockStatic(Files.class); PowerMockito.when(Files.newBufferedWriter(ArgumentMatchers.any(Path.class))).thenThrow(new IOException()); Path path = Paths.get("../qrda-files/valid-QRDA-III-latest.xml"); ConversionFileWriterWrapper converterWrapper = new ConversionFileWriterWrapper(path); converterWrapper.transform(); assertFileDoesNotExists("valid-QRDA-III-latest.qpp.json"); }
@Test @PrepareForTest({Files.class, ConversionFileWriterWrapper.class}) public void testFailureToWriteErrors() throws IOException { PowerMockito.mockStatic(Files.class); PowerMockito.when(Files.newBufferedWriter(ArgumentMatchers.any(Path.class))).thenThrow(new IOException()); Path path = Paths.get("src/test/resources/not-a-QRDA-III-file.xml"); ConversionFileWriterWrapper converterWrapper = new ConversionFileWriterWrapper(path); converterWrapper.transform(); assertFileDoesNotExists("not-a-QRDA-III-file.err.json"); }
@Test @PrepareForTest(WXImageView.class) public void testInitComponentHostView() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); assertEquals(imageView.getClass(), WXImageView.class); }
@Test @PrepareForTest(WXImageView.class) public void testSetBackgroundColor() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setBackgroundColor("#FFFFFF"); Drawable drawable = mWXImage.getHostView().getBackground(); assertEquals(drawable instanceof BorderDrawable, true); }
@PrepareForTest({ BridgeSerializationUtils.class }) @Test public void getHash() { PowerMockito.mockStatic(BridgeSerializationUtils.class); PowerMockito.when(BridgeSerializationUtils.serializePendingFederation(pendingFederation)).thenReturn(new byte[] { (byte) 0xaa }); Sha3Hash expectedHash = new Sha3Hash(HashUtil.sha3(new byte[] { (byte) 0xaa })); Assert.assertEquals(expectedHash, pendingFederation.getHash()); }
@Test @Parameters @PrepareForTest(YeelightDevice.class) public void setColorTemperatureTest(int colorTemp, YeelightCommand expectedSentCommand) throws Exception { YeelightDevice device = createTestingDevice(expectedSentCommand); device.setColorTemperature(colorTemp); }
@Test @Parameters @PrepareForTest(YeelightDevice.class) public void setRGBTest(int r, int g, int b, YeelightCommand expectedSentCommand) throws Exception { YeelightDevice device = createTestingDevice(expectedSentCommand); device.setRGB(r, g, b); }
@Test @Parameters @PrepareForTest(YeelightDevice.class) public void setHSVTest(int hue, int sat, YeelightCommand expectedSentCommand) throws Exception { YeelightDevice device = createTestingDevice(expectedSentCommand); device.setHSV(hue, sat); }
@Test @Parameters @PrepareForTest(YeelightDevice.class) public void setBrightnessTest(int brightness, YeelightCommand expectedSentCommand) throws Exception { YeelightDevice device = createTestingDevice(expectedSentCommand); device.setBrightness(brightness); }
@Test @Parameters @PrepareForTest(YeelightDevice.class) public void setPowerTest(boolean power, YeelightCommand expectedSentCommand) throws Exception { YeelightDevice device = createTestingDevice(expectedSentCommand); device.setPower(power); }