我是靠谱客的博主 现代云朵,这篇文章主要介绍预期的异常规则和模拟静态方法– JUnit,现在分享给大家,希望可以做个参考。

今天,我被要求使用RESTful服务,所以我开始遵循Robert Cecil Martin的TDD规则实施该服务,并遇到了一种测试预期异常以及错误消息的新方法(对我来说至少是这样),因此考虑共享我的实现方式作为这篇文章的一部分。

首先,让我们编写一个@Test并指定规则,我们的代码将为我们的示例抛出特定的异常,即EmployeeServiceException ,我们将使用ExpectedException对其进行验证,这将为我们提供有关预期抛出的异常的更精确信息,并具有验证的能力错误消息,如下所示:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RunWith(PowerMockRunner.class) @PrepareForTest(ClassWithStaticMethod.class) public class EmployeeServiceImplTest { @InjectMocks private EmployeeServiceImpl employeeServiceImpl; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setupMock() { MockitoAnnotations.initMocks(this); } @Test public void addEmployeeForNull() throws EmployeeServiceException { expectedException.expect(EmployeeServiceException.class); expectedException.expectMessage("Invalid Request"); employeeServiceImpl.addEmployee(null); } }

现在,我们将为@Test创建一个实现类,该类将在请求为null时抛出EmployeeServiceException ,对我来说,它是EmployeeServiceImpl ,如下所示:

EmployeeServiceImpl.java

复制代码
1
2
3
4
5
6
7
8
9
10
public class EmployeeServiceImpl implements IEmployeeService { @Override public String addEmployee(final Request request) throws EmployeeServiceException { if (request == null) { throw new EmployeeServiceException("Invalid Request"); } return null; } }

下一步,我们将写一个@Test,我们将使用嘲笑其接受输入参数,返回类型的静态方法PowerMockito.mockStatic() ,验证它使用PowerMockito.verifyStatic(),最后做一个断言来记录测试通过或失败状态,如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test public void addEmployee() throws EmployeeServiceException { PowerMockito.mockStatic(ClassWithStaticMethod.class); PowerMockito.when(ClassWithStaticMethod.getDetails(anyString())) .thenAnswer(new Answer<String>() { @Override public 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语句的一部分 ,如下所示:

复制代码
1
2
3
4
5
6
7
8
9
10
11
public class EmployeeServiceImpl implements IEmployeeService { @Override public String addEmployee(final Request request) throws EmployeeServiceException { if (request == null) { throw new EmployeeServiceException("Invalid Request"); } else { return ClassWithStaticMethod.getDetails(request.getName()); } } }

其中getDetailsClassWithStaticMethod内部的静态方法:

复制代码
1
2
3
4
5
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的全部内容,更多相关预期的异常规则和模拟静态方法–内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部