当前位置: 首页 > 知识库问答 >
问题:

Mockito-PowerMock。模拟方法调用

薛高澹
2023-03-14
@Resource
private Bar bar;

public int methodToTest(String arg1) {
    String crucialValue = SomeClass.methodToMock(bar.getterToMock());
        Method Logic Here 
        ....
}
private BarContext barContext = mock(BarContext.class)
@Mock
private Bar bar;

@Test
public void testTheMethod(){
    PowerMockito.mockStatic(SomeClass.class);
    PowerMockito.doReturn(barContext).when(bar).getterToMock();
    PowerMockito.doReturn("Bingo").when(SomeClass.methodToMock(barContext));
    Foo foo = new Foo();
    foo.methodToTest("foo");
}
@WebService
public class FileUploadServiceImpl implements FileUploadService {

private final String soapFilePath = "target/;
private final static Map<String, String> userFileMap = new HashMap<>();
private final static AtomicInteger id = new AtomicInteger();

@Resource
private WebServiceContext webServiceContext;

@Override
public int createFile(@WebParam String name) {
    String username = Utils.getUsername(webServiceContext.getMessageContext());

    try {
        File userDir = new File(filePath + username);
        userDir.mkdir();
        File file = new File(userDir.getPath() + "/" + name);
        file.createNewFile();
        userFileMap.put(username + "_" + id.get(), name);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        e.printStackTrace();
    }
    return id.getAndIncrement();
   }
}
public static String getUsername(MessageContext context){
            Map httpHeaders = (Map) context.get(MessageContext.HTTP_REQUEST_HEADERS);
            if(httpHeaders != null){
                List<String> auth = (List<String>) httpHeaders.get("Authorization");
                if (auth != null && auth.get(0).startsWith("Basic")){
                    String base64Credentials = auth.get(0).substring("Basic".length()).trim();
                    String credentials = new String(Base64.getDecoder().decode(
                            base64Credentials.getBytes(Charset.forName("UTF-8"))));
                    return credentials.split(":", 2)[0];
                }
            }
        return null;
      }
@RunWith(PowerMockRunner.class)
@PrepareForTest(FileUploadServiceImpl.class)
public class ServiceTest {
private String username = "10237832";
private FileUploadService service;
private MessageContext messageContext = mock(MessageContext.class);

@Mock
private WebServiceContext webServiceContext;

@Test
public void startUploadFileTest(){
    service = new FileUploadServiceImpl();
    mockStatic(Utils.class);
    when(webServiceContext.getMessageContext()).thenReturn(messageContext);
    when(Utils.getUsername(messageContext)).thenReturn(username);
    service.startUpload("test_file");
  }
}

异常堆栈跟踪

java.lang.NullPointerException
    at org.example.utils.Utils.getUsername(Utils.java:47)
    at org.example.services.ServiceTest.startUploadFileTest(ServiceTest.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

共有1个答案

云啸
2023-03-14

为什么不将用户名的获取抽象到一个类中呢?

    class UsernameRetriever {

        private final WebServiceContext webServiceContext;

        UsernameRetriever(WebServiceContext webServiceContext) {
           this.webServiceContext = webServiceContext;
        }


        String getUsernameFromContext() {
            return Utils.getUsername(webServiceContext.getMessageContext());
        }

    }

然后通过构造函数将其注入到类中(我不记得@inject和构造函数的语法,所以您自己查看一下)。

@WebService
public class FileUploadServiceImpl implements FileUploadService {

// SHOULD BE STATIC FINAL IF IT'S A CONSTANT - IT SHOULD BE PARAMETRIZED BTW
private static final String soapFilePath = "target/;
// YOU'RE GOING TO HAVE A RACE CONDITION - HASH MAP IS NOT THREAD SAFE
private final static Map<String, String> userFileMap = new HashMap<>();
private final static AtomicInteger id = new AtomicInteger();

private final UsernameRetriver usernameRetriever;

@Inject
public FileUploadServiceImpl(WebServiceContext webServiceContext) {
    this.usernameRetriever = new UsernameRetriever(webServiceContext);
}


@Inject
// for testing purposes
FileUploadServiceImpl(UsernameRetriever usernameRetriever) {
    this.usernameRetriever = usernameRetriever
}

@Override
public int createFile(@WebParam String name) {
    String username = usernameRetriever.getUsernameFromContext();

    try {
        File userDir = new File(filePath + username);
        userDir.mkdir();
        File file = new File(userDir.getPath() + "/" + name);
        file.createNewFile();
        userFileMap.put(username + "_" + id.get(), name);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        e.printStackTrace();
    }
    return id.getAndIncrement();
   }
}

这样:*不需要Powermock*您只负责*您已经正确地编写了代码;)

 类似资料:
  • 我正在尝试使用JUnit、Mockito和PowerMock验证对的调用。 下面是我的测试用例: 下面是测试中的代码: 非常有趣的是,这段代码失败时出现:

  • 问题内容: 这是我的代码- 我想在课堂上嘲笑。但是我找不到解决办法。仅禁止并返回默认值(在上述情况下为0)。事情就是这样,,只对静态方法的工作。 有没有办法在Powermock中做到这一点? 我正在使用Powermock 1.5和Mockito 1.9.5。 问题答案: 看来jMockit可以满足我的需求。也许我可以将这个问题发布到powermock邮件列表中。同时下面就足够了。包learning

  • 当我尝试使用mockito和powermock(在testng框架下使用)来模拟这些变量时,我遇到了一个问题 到目前为止我所做的 但是当我试图运行上面的代码时,我得到了以下错误: > 您使用以下任一方法存根:final/private/equals()/hashCode()方法。这些方法不能被截取/验证。不支持在非公共父类上声明的模拟方法。 在when()中,您不是在mock上调用method而是

  • 我正在尝试测试下一种方法: 称为PrivateMethod: asyncTask的执行无法在Mockito的测试中完成,所以我需要以某种方式模拟它。我试着用PowerMock来嘲弄私有方法: 这在PowerMockito行(NullPointerException)中给了我一个异常,它说 方法引发了“org.mockito.exceptions.Misusing.UnfinishedStubbin

  • 问题内容: 我有以下要模拟的Logger,但要验证是否正在调用日志条目,而不是内容。 我想模拟用于LoggerFactory.getLogger()的任何类,但是我找不到如何做到这一点。到目前为止,这是我最终得到的结果: 我想知道: 我可以模拟静态模型以用于任何课程吗? 我只能似乎运行的,因此我似乎无法改变每个方法的特点。有没有解决的办法? 编辑结果: 我以为我已经尝试过了,但没有成功: 但是,谢

  • 问题内容: 我有四个让我们说A,B,C,D的类,每个类都从另一个调用方法。 现在我已经模拟了类A,并且想模拟使用嘲笑的方法 并希望在递归方法调用上获取“ foo” 应该回来 我试过了 when(a.getB()。getC()。getD())。thenReturn(“ foo”); 但是得到了nullPointerException 然后我尝试 doReturn(“ foo”)。when(a.get