Java Code Examples for org.powermock.api.mockito.PowerMockito#spy()

The following examples show how to use org.powermock.api.mockito.PowerMockito#spy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoveWorkflowServletTest.java    From hop with Apache License 2.0 7 votes vote down vote up
@Test
@PrepareForTest( { Encode.class } )
public void testRemoveWorkflowServletEscapesHtmlWhenPipelineNotFound() throws ServletException, IOException {
  HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
  HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );

  StringWriter out = new StringWriter();
  PrintWriter printWriter = new PrintWriter( out );

  PowerMockito.spy( Encode.class );
  when( mockHttpServletRequest.getContextPath() ).thenReturn( RemoveWorkflowServlet.CONTEXT_PATH );
  when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
  when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );

  removeWorkflowServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
  assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );

  PowerMockito.verifyStatic( atLeastOnce() );
  Encode.forHtml( anyString() );
}
 
Example 2
Source File: SniffStepServletTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
@PrepareForTest( { Encode.class } )
public void testSniffStepServletEscapesHtmlWhenTransNotFound() throws ServletException, IOException {
  HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
  HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );

  StringWriter out = new StringWriter();
  PrintWriter printWriter = new PrintWriter( out );

  PowerMockito.spy( Encode.class );
  when( mockHttpServletRequest.getContextPath() ).thenReturn( SniffStepServlet.CONTEXT_PATH );
  when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
  when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );

  sniffStepServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
  assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );

  PowerMockito.verifyStatic( atLeastOnce() );
  Encode.forHtml( anyString() );
}
 
Example 3
Source File: DatabaseTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void updateChildren() throws Exception {
    // Given
    PowerMockito.mockStatic(QueryUpdateChildren.class);
    Database database = new Database();
    QueryUpdateChildren query = PowerMockito.spy(new QueryUpdateChildren(database, "/test"));
    PowerMockito.whenNew(QueryUpdateChildren.class).withAnyArguments().thenReturn(query);
    when(query.withArgs(Mockito.any())).thenReturn(query);
    Map data = Mockito.mock(Map.class);

    // When
    database.inReference("/test").updateChildren(data);

    // Then
    PowerMockito.verifyNew(QueryUpdateChildren.class);
}
 
Example 4
Source File: LocalFileSystemStorageTest.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
public void testStore() throws Exception {
  PowerMockito.spy(FileUtils.class);
  PowerMockito.doReturn(true).when(FileUtils.class, "createDirectory", anyString());
  PowerMockito.doReturn(true).when(FileUtils.class, "isFileExists", anyString());
  PowerMockito.doReturn(true).when(FileUtils.class, "isDirectoryExists", anyString());
  PowerMockito.doReturn(true)
      .when(FileUtils.class, "writeToFile", anyString(), any(byte[].class), anyBoolean());
  PowerMockito.doReturn(false).when(FileUtils.class, "hasChildren", anyString());

  Checkpoint mockCheckpoint = mock(Checkpoint.class);
  when(mockCheckpoint.getCheckpoint()).thenReturn(checkpoint);

  final CheckpointInfo info = new CheckpointInfo(
      StatefulStorageTestContext.CHECKPOINT_ID, instance);
  localFileSystemStorage.storeCheckpoint(info, mockCheckpoint);

  PowerMockito.verifyStatic(times(1));
  FileUtils.writeToFile(anyString(), eq(checkpoint.toByteArray()), eq(true));
}
 
Example 5
Source File: UTest.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsDesktopModeActive() {
    PowerMockito.spy(U.class);
    BooleanAnswer isDesktopModeSupportedAnswer = new BooleanAnswer();
    IntAnswer getExternalDisplayIdAnswer = new IntAnswer();
    BooleanAnswer hasFreeformSupportAnswer = new BooleanAnswer();
    when(U.isDesktopModeSupported(context)).thenAnswer(isDesktopModeSupportedAnswer);
    when(U.getExternalDisplayID(context)).thenAnswer(getExternalDisplayIdAnswer);
    when(U.hasFreeformSupport(context)).thenAnswer(hasFreeformSupportAnswer);

    isDesktopModeSupportedAnswer.answer = false;
    assertFalse(U.isDesktopModeActive(context));

    isDesktopModeSupportedAnswer.answer = true;
    Settings.Global.putInt(
            context.getContentResolver(),
            "force_desktop_mode_on_external_displays",
            0
    );
    assertFalse(U.isDesktopModeActive(context));
    Settings.Global.putInt(
            context.getContentResolver(),
            "force_desktop_mode_on_external_displays",
            1
    );
    assertFalse(U.isDesktopModeActive(context));
    getExternalDisplayIdAnswer.answer = 1;
    assertFalse(U.isDesktopModeActive(context));
    hasFreeformSupportAnswer.answer = true;
    assertTrue(U.isDesktopModeActive(context));
    Settings.Global.putInt(
            context.getContentResolver(),
            "force_desktop_mode_on_external_displays",
            0
    );
}
 
Example 6
Source File: HeimdallElasticSearchRepositoryTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getDataFromESTest1() throws Exception {
	esUrl = "esUrl";
	final HeimdallElasticSearchRepository classUnderTest = PowerMockito.spy(new HeimdallElasticSearchRepository());
	ReflectionTestUtils.setField(classUnderTest, "esUrl", "esUrl123");
	mockStatic(StringBuilder.class);
	mockStatic(PacHttpUtils.class);
	PowerMockito.when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(Exception.class);
	final StringBuilder mock = PowerMockito.spy(new StringBuilder());
	PowerMockito.whenNew(StringBuilder.class).withAnyArguments().thenReturn(mock);
	assertThatThrownBy(() -> classUnderTest.getEventsProcessed()).isInstanceOf(Exception.class);
}
 
Example 7
Source File: JSDebuggerWebSocketClientTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void test_loadApplicationScript_ShouldSendCorrectMessage() throws Exception {
  final JSDebuggerWebSocketClient.JSDebuggerCallback cb =
    PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class);

  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());
  HashMap<String, String> injectedObjects = new HashMap<>();
  injectedObjects.put("key1", "value1");
  injectedObjects.put("key2", "value2");

  client.loadApplicationScript("http://localhost:8080/index.js", injectedObjects, cb);
  PowerMockito.verifyPrivate(client).invoke("sendMessage", 0,
    "{\"id\":0,\"method\":\"executeApplicationScript\",\"url\":\"http://localhost:8080/index.js\"" +
    ",\"inject\":{\"key1\":\"value1\",\"key2\":\"value2\"}}");
}
 
Example 8
Source File: UTest.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private void testGetActivityOptions(int defaultStackId,
                                    int freeformStackId,
                                    int stackIdWithoutBrokenApi) {
    PowerMockito.spy(U.class);
    BooleanAnswer hasBrokenSetLaunchBoundsApiAnswer = new BooleanAnswer();
    BooleanAnswer isChromeOsAnswer = new BooleanAnswer();
    when(U.hasBrokenSetLaunchBoundsApi()).thenAnswer(hasBrokenSetLaunchBoundsApiAnswer);
    when(U.isChromeOs(context)).thenAnswer(isChromeOsAnswer);
    boolean originFreeformHackActive = FreeformHackHelper.getInstance().isFreeformHackActive();
    checkActivityOptionsStackIdForNonContextMenu(
            context, null, false, defaultStackId
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.APP_PORTRAIT, false, 1
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.APP_PORTRAIT, true, freeformStackId
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.APP_LANDSCAPE, false, 1
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.APP_LANDSCAPE, true, freeformStackId
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.APP_FULLSCREEN, false, 1
    );
    checkActivityOptionsStackIdForNonContextMenu(
            context, ApplicationType.FREEFORM_HACK, false, freeformStackId
    );
    FreeformHackHelper.getInstance().setFreeformHackActive(originFreeformHackActive);
    hasBrokenSetLaunchBoundsApiAnswer.answer = true;
    checkActivityOptionsStackIdForContextMenu(context, 1);
    hasBrokenSetLaunchBoundsApiAnswer.answer = false;
    isChromeOsAnswer.answer = false;
    checkActivityOptionsStackIdForContextMenu(context, stackIdWithoutBrokenApi);
    isChromeOsAnswer.answer = true;
    checkActivityOptionsStackIdForContextMenu(context, -1);
}
 
Example 9
Source File: AllocateServerSocketServletTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
@PrepareForTest( { Encode.class } )
public void testAllocateServerSocketServletEncodesParametersForHmtlResponse() throws ServletException,
  IOException {
  HttpServletRequest mockRequest = mock( HttpServletRequest.class );
  HttpServletResponse mockResponse = mock( HttpServletResponse.class );
  SocketPortAllocation mockSocketPortAllocation = mock( SocketPortAllocation.class );
  PowerMockito.spy( Encode.class );
  final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  ServletOutputStream servletOutputStream = new ServletOutputStream() {

    @Override
    public void write( int b ) throws IOException {
      byteArrayOutputStream.write( b );
    }
  };

  when( mockRequest.getContextPath() ).thenReturn( AllocateServerSocketServlet.CONTEXT_PATH );
  when( mockRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
  when( mockResponse.getOutputStream() ).thenReturn( servletOutputStream );
  when(
    mockTransformationMap.allocateServerSocketPort(
      anyInt(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
      anyString(), anyString() ) ).thenReturn( mockSocketPortAllocation );
  allocateServerSocketServlet.doGet( mockRequest, mockResponse );

  String response = byteArrayOutputStream.toString();
  // Pull out dynamic part of body, remove hardcoded html
  String dynamicBody =
    ServletTestUtils
      .getInsideOfTag( "BODY", response ).replaceAll( "<p>", "" ).replaceAll( "<br>", "" ).replaceAll(
        "<H1>.+</H1>", "" ).replaceAll( "--> port", "" );
  assertFalse( ServletTestUtils.hasBadText( dynamicBody ) );
  PowerMockito.verifyStatic( atLeastOnce() );
  Encode.forHtml( anyString() );
}
 
Example 10
Source File: LocalFileSystemStorageTest.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Test
public void testDispose() throws Exception {
  PowerMockito.spy(FileUtils.class);
  PowerMockito.doReturn(true).when(FileUtils.class, "deleteDir", anyString());
  PowerMockito.doReturn(false).when(FileUtils.class, "isDirectoryExists", anyString());

  localFileSystemStorage.dispose("", true);

  PowerMockito.verifyStatic(times(1));
  FileUtils.deleteDir(anyString());
  FileUtils.isDirectoryExists(anyString());
}
 
Example 11
Source File: LauncherHelperTest.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    launcherHelper = LauncherHelper.getInstance();
    context = ApplicationProvider.getApplicationContext();
    assertNotNull(context);

    PowerMockito.spy(U.class);
    getExternalDisplayIdAnswer = new IntAnswer();
    when(U.getExternalDisplayID(context)).thenAnswer(getExternalDisplayIdAnswer);
}
 
Example 12
Source File: UserDataSchemaCacheTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * isChangedメソッドでキャッシュ無効化時間が登録済みのキャッシュと異なる場合trueを返すこと.
 * @throws Exception 実行エラー
 */
@Test
public void isChangedメソッドでキャッシュ無効化時間が登録済みのキャッシュと異なる場合trueを返すこと() throws Exception {
    String nodeId = "node_VVVVVVVVV1";
    Map<String, Object> schemaToCache = new HashMap<String, Object>();
    schemaToCache.put("SchemaCacheTestKey001", "testValue");
    Long now = new Date().getTime();
    schemaToCache.put("disabledTime", now);

    // テスト用のキャッシュクラスに接続するよう設定を変更
    MockMemcachedClient mockMemcachedClient = new MockMemcachedClient();
    PowerMockito.spy(UserDataSchemaCache.class);
    PowerMockito.when(UserDataSchemaCache.class, "getMcdClient").thenReturn(mockMemcachedClient);

    // キャッシュの設定を有効にする
    PowerMockito.spy(DcCoreConfig.class);
    PowerMockito.when(DcCoreConfig.class, "isSchemaCacheEnabled").thenReturn(true);

    // 事前にキャッシュを登録する
    UserDataSchemaCache.cache(nodeId, schemaToCache);

    // isChanged?
    Map<String, Object> schemaToCacheNew = new HashMap<String, Object>();
    schemaToCacheNew.put("SchemaCacheTestKey002", "testValue");
    schemaToCacheNew.put("disabledTime", now + 1);
    assertThat(UserDataSchemaCache.isChanged(nodeId, schemaToCacheNew)).isTrue();
}
 
Example 13
Source File: CommonUtilsTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the query.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("unchecked")
@Test
public void buildQuery() throws Exception {
	Map<String, Object> mustFilterDetails = Maps.newHashMap();
	Gson gson = new Gson();
	String jsonObject = "{\"count\":\"123\",\"hits\":{\"total\":1000,\"max_score\":null,\"hits\":[{\"_index\":\"bank\",\"_type\":\"_doc\",\"_id\":\"0\",\"sort\":[0],\"_score\":null,\"_source\":{\"account_number\":0,\"balance\":16623,\"firstname\":\"Bradshaw\",\"lastname\":\"qwe\",\"age\":29,\"gender\":\"F\",\"address\":\"2133\",\"employer\":\"123\",\"email\":\"[email protected]\",\"city\":\"Hobucken\",\"state\":\"CO\"}}]},\"aggregations\":{\"avg-values-per-day\":{\"buckets\":[{\"key_as_string\":\"ID\",\"Avg-CPU-Utilization\":{\"value\":12},\"Avg-NetworkIn\":{\"value\":12},\"Avg-NetworkOut\":{\"value\":12},\"Avg-DiskReadinBytes\":{\"value\":12},\"Avg-DiskWriteinBytes\":{\"value\":12}}]}}}";
	Map<String, Object> json = (Map<String, Object>) gson.fromJson(jsonObject, Object.class);
	mustFilterDetails.put("has_child", "has_child123");
	HashMultimap<String, Object> shouldFilter = HashMultimap.create();
	shouldFilter.put("has_child", mustFilterDetails);
	final CommonUtils classUnderTest = PowerMockito.spy(new CommonUtils());
	Whitebox.invokeMethod(classUnderTest, "buildQuery", json, json, shouldFilter);
}
 
Example 14
Source File: WXTextDomObjectTest.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeasure() throws Exception {
  testLayoutBefore();
  MeasureOutput output = new MeasureOutput();
  WXTextDomObject mock = PowerMockito.spy(dom);
  PowerMockito.when(mock,"getTextWidth",dom.getTextPaint(),100f,false).thenReturn(10f);
  WXTextDomObject.TEXT_MEASURE_FUNCTION.measure(mock,100,output);

  assertEquals(output.width,10f,0.1f);
}
 
Example 15
Source File: JSDebuggerWebSocketClientTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void test_executeJSCall_ShouldSendCorrectMessage() throws Exception {
  final JSDebuggerWebSocketClient.JSDebuggerCallback cb =
    PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class);

  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());

  client.executeJSCall("foo", "[1,2,3]", cb);
  PowerMockito.verifyPrivate(client).invoke("sendMessage", 0,
    "{\"id\":0,\"method\":\"foo\",\"arguments\":[1,2,3]}");
}
 
Example 16
Source File: UTest.java    From Taskbar with Apache License 2.0 4 votes vote down vote up
@Test
public void testEnableFreeformModeShortcut() {
    PowerMockito.spy(U.class);
    BooleanAnswer canEnableFreeformAnswer = new BooleanAnswer();
    BooleanAnswer isOverridingFreeformHackAnswer = new BooleanAnswer();
    BooleanAnswer isChromeOsAnswer = new BooleanAnswer();
    when(U.canEnableFreeform()).thenAnswer(canEnableFreeformAnswer);
    when(U.isOverridingFreeformHack(context, false))
            .thenAnswer(isOverridingFreeformHackAnswer);
    when(U.isChromeOs(context)).thenAnswer(isChromeOsAnswer);

    canEnableFreeformAnswer.answer = false;
    isOverridingFreeformHackAnswer.answer = false;
    isChromeOsAnswer.answer = false;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = false;
    isOverridingFreeformHackAnswer.answer = false;
    isChromeOsAnswer.answer = true;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = false;
    isOverridingFreeformHackAnswer.answer = true;
    isChromeOsAnswer.answer = false;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = false;
    isOverridingFreeformHackAnswer.answer = true;
    isChromeOsAnswer.answer = true;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = true;
    isOverridingFreeformHackAnswer.answer = false;
    isChromeOsAnswer.answer = false;
    assertTrue(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = true;
    isOverridingFreeformHackAnswer.answer = false;
    isChromeOsAnswer.answer = true;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = true;
    isOverridingFreeformHackAnswer.answer = true;
    isChromeOsAnswer.answer = false;
    assertFalse(U.enableFreeformModeShortcut(context));

    canEnableFreeformAnswer.answer = true;
    isOverridingFreeformHackAnswer.answer = true;
    isChromeOsAnswer.answer = true;
    assertFalse(U.enableFreeformModeShortcut(context));
}
 
Example 17
Source File: MarathonControllerTest.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
/***
 * Test MarathonController's restartApp method
 * @throws Exception
 */
@Test
public void testRestartApp() throws Exception {
  HttpURLConnection httpURLConnection = Mockito.mock(HttpURLConnection.class);
  int appId = 0;

  // Failed to get connection
  PowerMockito.spy(NetworkUtils.class);
  PowerMockito.doReturn(httpURLConnection)
      .when(NetworkUtils.class, "getHttpConnection", Mockito.anyString());
  Assert.assertFalse(controller.restartApp(appId));
  PowerMockito.verifyStatic();
  NetworkUtils.getHttpConnection(Mockito.anyString());

  // Failed to send request
  PowerMockito.spy(NetworkUtils.class);
  PowerMockito.doReturn(httpURLConnection)
      .when(NetworkUtils.class, "getHttpConnection", Mockito.anyString());
  PowerMockito.doReturn(false)
      .when(NetworkUtils.class, "sendHttpPostRequest",
          Mockito.any(HttpURLConnection.class),
          Mockito.anyString(),
          Mockito.any(byte[].class));
  Assert.assertFalse(controller.restartApp(appId));
  PowerMockito.verifyStatic();
  NetworkUtils.getHttpConnection(Mockito.anyString());
  NetworkUtils.sendHttpPostRequest(
      Mockito.any(HttpURLConnection.class),
      Mockito.anyString(),
      Mockito.any(byte[].class));

  // Failed to get response
  PowerMockito.spy(NetworkUtils.class);
  PowerMockito.doReturn(httpURLConnection)
      .when(NetworkUtils.class, "getHttpConnection", Mockito.anyString());
  PowerMockito.doReturn(true)
      .when(NetworkUtils.class, "sendHttpPostRequest",
          Mockito.any(HttpURLConnection.class),
          Mockito.anyString(),
          Mockito.any(byte[].class));
  PowerMockito.doReturn(false)
      .when(NetworkUtils.class, "checkHttpResponseCode",
          Mockito.any(HttpURLConnection.class), Mockito.anyInt());
  Assert.assertFalse(controller.restartApp(appId));
  PowerMockito.verifyStatic();
  NetworkUtils.getHttpConnection(Mockito.anyString());
  NetworkUtils.sendHttpPostRequest(
      Mockito.any(HttpURLConnection.class),
      Mockito.anyString(),
      Mockito.any(byte[].class));
  NetworkUtils.checkHttpResponseCode(Mockito.any(HttpURLConnection.class), Mockito.anyInt());

  // Failed authentication
  PowerMockito.spy(NetworkUtils.class);
  PowerMockito.doReturn(httpURLConnection)
      .when(NetworkUtils.class, "getHttpConnection", Mockito.anyString());
  PowerMockito.doReturn(true)
      .when(NetworkUtils.class, "sendHttpPostRequest",
          Mockito.any(HttpURLConnection.class),
          Mockito.anyString(),
          Mockito.any(byte[].class));
  PowerMockito.doReturn(false)
      .when(NetworkUtils.class, "checkHttpResponseCode",
          Mockito.any(HttpURLConnection.class), Mockito.anyInt());
  PowerMockito.doReturn(true)
      .when(NetworkUtils.class, "checkHttpResponseCode",
          httpURLConnection, HttpURLConnection.HTTP_UNAUTHORIZED);
  Assert.assertFalse(controller.restartApp(appId));
  PowerMockito.verifyStatic();
  NetworkUtils.getHttpConnection(Mockito.anyString());
  NetworkUtils.sendHttpPostRequest(
      Mockito.any(HttpURLConnection.class),
      Mockito.anyString(),
      Mockito.any(byte[].class));
  NetworkUtils.checkHttpResponseCode(Mockito.any(HttpURLConnection.class), Mockito.anyInt());
  NetworkUtils.checkHttpResponseCode(httpURLConnection, HttpURLConnection.HTTP_UNAUTHORIZED);

  // Success
  PowerMockito.spy(NetworkUtils.class);
  PowerMockito.doReturn(httpURLConnection)
      .when(NetworkUtils.class, "getHttpConnection", Mockito.anyString());
  PowerMockito.doReturn(true)
      .when(NetworkUtils.class, "sendHttpPostRequest",
          Mockito.any(HttpURLConnection.class),
          Mockito.anyString(),
          Mockito.any(byte[].class));
  PowerMockito.doReturn(true)
      .when(NetworkUtils.class, "checkHttpResponseCode",
          Mockito.any(HttpURLConnection.class), Mockito.anyInt());
  Assert.assertTrue(controller.restartApp(appId));
  PowerMockito.verifyStatic();
  NetworkUtils.getHttpConnection(Mockito.anyString());
  NetworkUtils.sendHttpPostRequest(
      Mockito.any(HttpURLConnection.class),
      Mockito.anyString(),
      Mockito.any(byte[].class));
  NetworkUtils.checkHttpResponseCode(Mockito.any(HttpURLConnection.class), Mockito.anyInt());
}
 
Example 18
Source File: GetAssociationIndicationStatusTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
	// Instantiate a local XBeeDevice object.
	xbeeDevice = PowerMockito.spy(new XBeeDevice(Mockito.mock(SerialPortRxTx.class)));
}
 
Example 19
Source File: XBeeNetworkConfigurationTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeNetwork#addRemoteDevices(java.util.List)}.
 * 
 * Add a list of devices to not empty network and a already existing device.
 */
@Test
public final void testAddRemoteDevicesToNetworkWithAlreadyExistingDevices() {
	// Setup the resources for the test.
	List<RemoteXBeeDevice> list = new ArrayList<RemoteXBeeDevice>(0);
	for (int i = 0; i < 3; i++)
		list.add(new RemoteXBeeDevice(deviceMock, 
				new XBee64BitAddress("0013A20040A9E78"+i), 
				XBee16BitAddress.UNKNOWN_ADDRESS, "id"+i));
	
	RemoteXBeeDevice deviceAlreadyInNetwork = PowerMockito.spy(
			new RemoteXBeeDevice(deviceMock, 
			new XBee64BitAddress("0013A20040A9E780"), 
			XBee16BitAddress.UNKNOWN_ADDRESS, "id0_old"));
	network.addRemoteDevice(deviceAlreadyInNetwork);
	
	// Verify the result.
	Map<XBee64BitAddress, RemoteXBeeDevice> add64Map = Whitebox.<Map<XBee64BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy64BitAddr");
	Map<XBee16BitAddress, RemoteXBeeDevice> add16Map = Whitebox.<Map<XBee16BitAddress, RemoteXBeeDevice>> getInternalState(network, "remotesBy16BitAddr");
	
	assertThat(add64Map.size(), is(equalTo(1)));
	assertThat(add16Map.size(), is(equalTo(0)));
	
	// Call the method under test.
	List<RemoteXBeeDevice> added = network.addRemoteDevices(list);
	
	assertThat(add64Map.size(), is(equalTo(3)));
	assertThat(add16Map.size(), is(equalTo(0)));
	
	Mockito.verify(network, Mockito.times(list.size() + 1 /*We are adding in the setup*/)).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class));
	
	assertThat("Returned list must contain " + list.size(), added.size(), is(equalTo(list.size())));
	assertThat("The network must contain " + list.size(), network.getNumberOfDevices(), is(equalTo(list.size())));
	assertThat("The added reference and the returned must be the different", list == added, is(equalTo(false)));
	
	Mockito.verify(deviceAlreadyInNetwork, Mockito.times(1)).updateDeviceDataFrom(list.get(0));
	assertThat("The reference of existing device in the network and in the list to add must be different", 
			list.get(0) == added.get(0), is(equalTo(false)));
	for (int i = 1; i < list.size(); i++)
		assertThat("The device reference in the network and in the list to add must be the same", 
				list.get(i) == added.get(i), is(equalTo(true)));
}
 
Example 20
Source File: Set16BitAddressTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
	// Instantiate a local XBee device object.
	xbeeDevice = PowerMockito.spy(new XBeeDevice(Mockito.mock(SerialPortRxTx.class)));
}