[英]Powermockito whenNew returns null if not matched
我不知道它是否應該這樣做,但我想不是。 看下面我的代碼。
File mocked = PowerMockito.mock(File.class);
PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(eq(THE_TARGET_PATH)).thenReturn(mocked);
File normalFile = new File(WORKING_PATH);
File mockedFile = new File(THE_TARGET_PATH);
我確實希望normalFile
將正常創建,但實際上為null
。 正確地嘲笑了mockedFile
。
我也在使用@RunWith(PowerMockRunner.class)
和@PrepareForTest({ClassWhereInstanceIsCreated.class, File.class})
我正在使用:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
我的發現表明,沒有一種好的方法可以使用PowerMockito / PowerMockito 2進行部分構造函數模擬。通過邏輯,您應該能夠執行類似
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
.withArguments(eq(WORKING_PATH)).thenCallRealMethod();
但這會在PowerMockito中觸發類似於此的內部異常
org.mockito.exceptions.base.MockitoException:無法在Java對象上調用抽象的真實方法! 僅在模擬非抽象方法時才可以調用真實方法。 //正確的示例:when(mockOfConcreteClass.nonAbstractMethod())。thenCallRealMethod();
因此,我看到的唯一方法是重新編寫測試。 在模擬構造函數之前,應該首先構造所有必需的File
對象,並提供PowerMockito規則,該規則在每種情況下都將返回。
File mocked = Mockito.mock(File.class);
// create file as you want
File realFile = new File(WORKING_PATH);
// tell PowerMockito to return it
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
.withArguments(Mockito.eq(WORKING_PATH)).thenReturn(realFile);
// tell PowerMockito to return mock if other argument passed
PowerMockito.whenNew(File.class).withParameterTypes(String.class)
.withArguments(Mockito.eq(THE_TARGET_PATH)).thenReturn(mocked);
File normalFile = new File(WORKING_PATH);
File mockedFile = new File(THE_TARGET_PATH);
這是不受歡迎的解決方案,但是我無法提供更好的解決方案。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.