java单元测试测试异常_java单元测试
发布日期:2022-02-18 13:19:50 浏览次数:1 分类:技术文章

本文共 2354 字,大约阅读时间需要 7 分钟。

1.Junit

@Test : 测试方法,测试程序会运行的方法,后边可以跟参数代表不同的测试,如(expected=XXException.class) 异常测试,(timeout=xxx)超时测试

2. @Ignore : 被忽略的测试方法

3. @Before: 每一个测试方法之前运行

4. @After : 每一个测试方法之运行

5. @BeforeClass: 所有测试开始之前运行

6. @AfterClass: 所有测试结束之后运行

assertTrue(String message, boolean condition) 要求condition == true

assertFalse(String message, boolean condition) 要求condition == false

fail(String message) 必然失败,同样要求代码不可达

assertEquals(String message, XXX expected,XXX actual) 要求expected.equals(actual)

assertArrayEquals(String message, XXX[] expecteds,XXX [] actuals) 要求expected.equalsArray(actual)

assertNotNull(String message, Object object) 要求object!=null

assertNull(String message, Object object) 要求object==null

assertSame(String message, Object expected, Object actual) 要求expected == actual

assertNotSame(String message, Object unexpected,Object actual) 要求expected != actual

assertThat(String reason, T actual, Matcher matcher) 要求matcher.matches(actual) == true

2.mockito:

测试无参数函数mock

String mocked = "mocked Return";

Demo demo = Mockito.mock(Demo.class);

Mockito.when(demo.methodNoParameters()).thenReturn(mocked);

Assert.assertEquals(demo.methodNoParameters(), mocked);

2、构造有基本类型作为参数的返回

Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);

Assert.assertEquals(demo.speak("你好"), word);

3、构造有基本类型作为参数,但是只针对特定参数输入才mock返回值

Mockito.when(demo.speak(Mockito.matches(".*大爷$"))).thenReturn(word);

Assert.assertEquals(demo.speak("隔壁李大爷"), word);

4.构造mock的函数抛出异常

Mockito.when(demo.speak(Mockito.anyString())).thenThrow(new Exception());

5.某些反复调用,我们希望对于每次调用都返回不同的mock值

Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word).thenReturn(word1);

6.验证函数执行是否经过了mock

Mockito.when(demo.speak(Mockito.anyString())).thenReturn(word);

Assert.assertEquals(demo.speak("你猜"), word);

Mockito.verify(demo.speak("你猜"));

//下面这个参数的方法调用并没有被执行过,所以会抛出NotAMockException的异常

Mockito.verify(demo.speak("nicai"));

7.不光要对方法的返回值和调用进行验证,同时需要验证一系列交互后所传入方法的参数。

那么我们可以用参数捕获器来捕获传入方法的参数进行验证,看它是否符合我们的要求。

argument.capture() 捕获方法参数

argument.getValue() 获取方法参数值,如果方法进行了多次调用,它将返回最后一个参数值

argument.getAllValues() 方法进行多次调用后,返回多个参数值

boolean updated = personDAO.update( 1, "David" );

ArgumentCaptor personCaptor = ArgumentCaptor.forClass( Person.class );

verify( personDAO ).update( personCaptor.capture() );

Person updatedPerson = personCaptor.getValue();

assertEquals( "David", updatedPerson.getPersonName() );

转载地址:https://blog.csdn.net/weixin_28926205/article/details/114622196 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java获取引用名_在运行时Java中获取方法引用的名称是否可能(如何)?[复制品]
下一篇:java实现并行查询_java8中parallelStream提升数倍查询效率是怎样实现的,来看看这篇文章...

发表评论

最新留言

不错!
[***.144.177.141]2024年04月13日 19时02分15秒