预期的异常规则和模拟静态方法– JUnit
今天,我被要求使用RESTful服務,所以我開始遵循Robert Cecil Martin的TDD規則實施該服務,并遇到了一種測試預期異常以及錯誤消息的新方法(對我來說至少是這樣),因此考慮共享我的實現方式作為這篇文章的一部分。
首先,讓我們編寫一個@Test并指定規則,我們的代碼將為我們的示例拋出特定的異常,即EmployeeServiceException ,我們將使用ExpectedException對其進行驗證,這將為我們提供有關預期拋出的異常的更精確信息,并具有驗證的能力錯誤消息,如下所示:
@RunWith(PowerMockRunner.class) @PrepareForTest(ClassWithStaticMethod.class) public class EmployeeServiceImplTest {@InjectMocksprivate EmployeeServiceImpl employeeServiceImpl;@Rulepublic ExpectedException expectedException = ExpectedException.none();@Beforepublic void setupMock() {MockitoAnnotations.initMocks(this);}@Testpublic void addEmployeeForNull() throws EmployeeServiceException {expectedException.expect(EmployeeServiceException.class);expectedException.expectMessage("Invalid Request");employeeServiceImpl.addEmployee(null);}}現在,我們將為@Test創建一個實現類,該類將在請求為null時拋出EmployeeServiceException ,對我來說,它是EmployeeServiceImpl ,如下所示:
EmployeeServiceImpl.java
public class EmployeeServiceImpl implements IEmployeeService {@Overridepublic String addEmployee(final Request request)throws EmployeeServiceException {if (request == null) {throw new EmployeeServiceException("Invalid Request");}return null;} }下一步,我們將寫一個@Test,我們將使用嘲笑其接受輸入參數,返回類型的靜態方法PowerMockito.mockStatic() ,驗證它使用PowerMockito.verifyStatic(),最后做一個斷言來記錄測試通過或失敗狀態,如下:
@Testpublic void addEmployee() throws EmployeeServiceException {PowerMockito.mockStatic(ClassWithStaticMethod.class);PowerMockito.when(ClassWithStaticMethod.getDetails(anyString())).thenAnswer(new Answer<String>() {@Overridepublic String answer(InvocationOnMock invocation)throws Throwable {Object[] args = invocation.getArguments();return (String) args[0];}});final String response = employeeServiceImpl.addEmployee(new Request("Arpit"));PowerMockito.verifyStatic();assertThat(response, is("Arpit"));}現在,我們將在EmployeeServiceImpl自身中提供@Test的實現。 為此,讓我們修改EmployeeServiceImpl使其具有靜態方法調用,作為addEmployee的else語句的一部分 ,如下所示:
public class EmployeeServiceImpl implements IEmployeeService {@Overridepublic String addEmployee(final Request request)throws EmployeeServiceException {if (request == null) {throw new EmployeeServiceException("Invalid Request");} else {return ClassWithStaticMethod.getDetails(request.getName());}} }其中getDetails是ClassWithStaticMethod內部的靜態方法:
public class ClassWithStaticMethod {public static String getDetails(String name) {return name;} }完整的源代碼托管在github上 。
翻譯自: https://www.javacodegeeks.com/2017/01/expected-exception-rule-mocking-static-methods-junit.html
總結
以上是生活随笔為你收集整理的预期的异常规则和模拟静态方法– JUnit的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 挂住的拼音 可以这样造句
- 下一篇: jvm类加载机制和类加载器_在JVM之下