MockitoAnnotations.initMocks(this)导致无法模拟/间谍类java.lang.String Mockito无法模拟/间谍,因为:-最终类

时间:2020-08-11 01:12:01

标签: java unit-testing mocking mockito

所以我正在构建一个测试类,并具有以下设置功能:

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
         //do other set up stuff
    }

当我在没有MockitoAnnotations.initMocks(this);的情况下运行测试类时,一切正常。但是,一旦我想添加模拟并添加initMocks语句,就会收到以下错误消息:

Cannot mock/spy class java.lang.String
Mockito cannot mock/spy because :
 - final class
org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy because :
 - final class
    at org.mockito.internal.runners.DefaultInternalRunner$1.withBefores(DefaultInternalRunner.java:38)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)

它是如此混乱,因为我不相信我在那里使用过字符串吗?我将类简化为一个断言1 == 1的测试,因此我知道错误并非来自测试。仅供参考,当我尝试使用@RunWith(MockitoJUnitRunner.class)时也会发生这种情况。有指针吗?谢谢!

0 个答案:

没有答案