同步wordpress站点,给人做logo的网站,flash as3 网站模板,注册网站要多少钱一年今天#xff0c;我被要求使用RESTful服务#xff0c;所以我开始遵循Robert Cecil Martin的TDD规则实施该服务#xff0c;并遇到了一种测试预期异常以及错误消息的新方法#xff08;对我来说至少是这样#xff09;#xff0c;因此考虑共享我的实现方式作为这篇文章的一部分… 今天我被要求使用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 AnswerString() {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