gpt4 book ai didi

unit-testing - 如何在最终类中模拟静态方法

转载 作者:行者123 更新时间:2023-12-02 11:19:35 29 4
gpt4 key购买 nike

我有一些代码在 final 类中有一个静态方法。我试图 mock 那个方法。我试过做一些事情..

public final Class Class1{

public static void doSomething(){
}
}

我如何模拟 doSomething()?我试过了..
Class1 c1=PowerMockito.mock(Class1.class)
PowerMockito.mockSatic(Class1.class);
Mockito.doNothing().when(c1).doSomething();

这给了我一个错误:
org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.cerner.devcenter.wag.textHandler.AssessmentFactory_Test.testGetGradeReport_HTMLAssessment(AssessmentFactory_Test.java:63)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!

at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260)

最佳答案

最常用的测试框架是 JUnit 4。因此,如果您正在使用它,则需要使用以下内容注释测试类:

@RunWith( PowerMockRunner.class )
@PrepareForTest( Class1.class )


PowerMockito.mockSatic(Class1.class);
Mockito.doNothing().when(c1).doSomething();

Mockito.when(Class1.doSomething()).thenReturn(fakedValue);

// call of static method is required to mock it
PowerMockito.doNothing().when(Class1.class);
Class1.doSomething();

关于unit-testing - 如何在最终类中模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700860/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com