带有注释方法的模拟类

时间:2011-09-14 16:23:35

标签: java unit-testing mocking easymock

我有一个我想要模拟的具体课程。有几种带注释的带注释的方法。我想创建类mock,但我需要保留这些注释。

我试过easymock。它可以毫无问题地为我的类创建子类,但不保留注释。

我想在easymock中保留注释。如果那是不可能的,还有其他任何嘲弄的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我更喜欢使用不同范例来模拟类的mockito。您不必像使用easymock那样对所有内容进行子类化。

http://code.google.com/p/mockito/

javadoc本身有大量关于如何利用库的信息

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#2

她的文档中有一个简短的例子。

//You can mock concrete classes, not only 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 before even verify() gets executed).
//If your code doesn't care what get(0) returns then it should 
not be stubbed. Not    convinced? See here.
verify(mockedList).get(0);

因此,使用此库可以设置测试并删除您感兴趣的测试方法。

希望你发现这很有用。