请参考下面有关于打标的代码。
//You can mock concrete classes, not just interfaces LinkedList mockedList = mock(LinkedList. class ); //stubbing when(mockedList.get( 0 )).thenReturn( "first" ); when(mockedList.get( 1 )).thenThrow( new RuntimeException()); //following prints "first" System.out.println(mockedList.get( 0 )); //following throws runtime exception System.out.println(mockedList.get( 1 )); //following prints "null" because get(999) was not stubbed System.out.println(mockedList.get( 999 )); //Although it is possible to verify a stubbed invocation, usually it‘s just redundant //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed). //If your code doesn‘t care what get(0) returns, then it should not be stubbed. verify(mockedList).get( 0 ); |
测试代码请访问 GitHub
请注意,上面的测试代码在运行的时候回出现错误。
这是因为在测试代码运行的时候,我们尝试输出 mockedList.get(1),这个在测试的时候,因为我们打标为抛出异常,所以这一句话将会在测试代码中抛出异常。
运行时候,抛出异常的界面如下:
https://www.cwiki.us/pages/viewpage.action?pageId=47843418
原文:https://www.cnblogs.com/huyuchengus/p/11540692.html