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创建一个实现类,该类将在请求为空时抛出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 静态方法