当前位置:网站首页>Mockito no return value method and exception mock

Mockito no return value method and exception mock

2022-06-09 06:32:00 ISaiSai

  1. No return value method exception mock
     doThrow(new RuntimeException()).when(testMethod).testMethod(anyString());
        Assertions.assertThrows(Exception.class, () -> testMethod.testMethod("foo"));
  1. Normal with return value mock
   given(testMethod.testMethodWithReturn(anyString())).willThrow(new Exception("TestError"));

perhaps

    when(testMethod.testMethodWithReturn(anyString())).thenThrow(new Exception("TestError"));
  1. Throw an exception based on a specific input parameter (answer Method )
        when(testMethod.testMethodWithReturn(anyString())).thenAnswer(
                new Answer() {
                    public Object answer(InvocationOnMock invocation) throws Exception {
                        Object[] args = invocation.getArguments();
                        if (args[0].equals("foo")) {
                            throw new Exception("mock  Abnormal response ");
                        }
                        return "ok";

                    }
                });
原网站

版权声明
本文为[ISaiSai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090625100651.html