==
我正在尝试在我的Scala代码中为Java上的单例枚举创建模拟,并引用here和here的引用。我无法更改此单例,因为它来自其他库,该单例的某些代码如下所示:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
以下是代码的一部分,但出现错误:
public enum singleton implements Isingleton {
INSTANCE;
public Command getCommand(String name) { <-- method to be mocked
....
}
....
}
错误是:
@RunWith(classOf[PowerMockRunner])
@PrepareForTest(Array(classOf[mySingleTon]))
class myTest {
@Test
def test(): Unit = {
val mockInstance = org.mockito.Mockito.mock[mySingleTon] //val mockInstance = org.powermock.api.mockito.PowerMockito.mock(classOf[mySingleTon])
Whitebox.setInternalState(classOf[mySingleTon], "INSTANCE":String, mockInstance:Any)
when(mockInstance.getAerospikeCommand(nameCapture.capture())).thenReturn(mockedFunc)
我也尝试按照建议的here进行以下操作:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class com.my.cap.myModule.Singleton
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
at org.scalatest.mock.MockitoSugar$class.mock(MockitoSugar.scala:74)
但后来我开始出现以下错误:
@RunWith(classOf[PowerMockRunner])
@PrepareForTest(Array(classOf[mySingleTon]))
class myTest {
@Test
def test(): Unit = {
import org.powermock.api.mockito.PowerMockito
PowerMockito.mockStatic(classOf[mySingleTon])
BDDMockito.given(mySingleTon.INSTANCE.getCommand(nameCapture.capture())).willReturn(mockedCommand)