簡體   English   中英

即使使用PowerMock也無法模擬java.net.URL?

[英]Not able to mock java.net.URL even by using PowerMock?

根據我的要求,我必須使用預先簽名的URL將文件上傳到Amazon S3,該URL是我從適用於我的AWS網站獲取的代碼,但現在我必須為使用PowerMockito的代碼編寫JUnit。模擬java.net。 URL,但根本不起作用。 以下是我的Java代碼以及無法正常工作的JUnit。 誰能給我解決方案,該如何進行? 提前致謝。
我的代碼:-

  


JUnit的

  

@InjectMocks
App app;

@Mock
URL url;

@Mock
OutputStream outStream;

@Test
public void uploadToS3_should_return_true() throws Exception{
    // no need to create instance of App, it should be initialyzed fine with @InjectMocks annotation
    // define mocked behavior   
    HttpURLConnection connection = PowerMockito.mock(HttpURLConnection.class);
    // mock connection and out stream methods
    PowerMockito.when(url.openConnection()).thenReturn(connection);
    PowerMockito.whenNew(URL.class).withArguments(Matchers.anyString()).thenReturn(url);

    PowerMockito.when(connection.getOutputStream()).thenReturn(outStream);
    PowerMockito.when(connection.getResponseCode()).thenReturn(200);

    // call action
    app.uploadToS3("http://something.com", "{}");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM