我有一个实现缓存的类,我想为其编写一个 JUnit 测试。
该类实现并接口(interface)了以下方法:
public void insert(Object key, Object value);
public Object getFromCache(Object key);
基本实现是单例。
我正在编写 JUnit 测试,但我不知道如何正确创建带有数据的虚拟缓存以便用于测试。
现在我正在做:
@Test
public void myTest() {
MyCache cache = MyCache.getInstance();
populateWithData(cache);
//test cache
asserEquals etc
}
如何避免使用 getInstance()
并且不在每个测试中填充?
最佳答案
显然我稍微误读了你的问题。
正如其他两个答案所述,如果您想拥有一个可以在运行每个测试用例时读取的特定缓存,您可以使用“@before”方法,该方法初始化要在测试用例中使用的对象。每个定义的“@before”方法都会在调用每个测试用例之前调用。这意味着您可以编写代码来实例化对象一次,而不是多次。
注意,如果您想在测试用例中执行不同的操作,请考虑在其顶部添加自定义,而不是编辑您的 @before
方法,因为这样将影响您的所有测试用例。
为了清楚起见,我将添加一些代码:
MyCache cache = null;
@before
public void initCache(){
cache = MyCache.getInstance();
populateWithData(cache);
}
// ... rest of your program here ...
原始答案:
如果您想对更复杂的对象进行更奇特的测试,可以使用它。这仍然可以与“@before”注释结合使用
你可以尝试mockito ...
这基本上是一个模拟函数或类的框架,您对完全实现它不感兴趣,特别是对于测试。
这是使用模拟关闭列表的示例:
import static org.mockito.Mockito.*;
// mock creation
List mockedList = mock(List.class);
// using mock object - it does not throw any "unexpected interaction" exception
mockedList.add("one");
mockedList.clear();
// selective, explicit, highly readable verification
verify(mockedList).add("one");
verify(mockedList).clear();
// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");
// the following prints "first"
System.out.println(mockedList.get(0));
// the following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
你基本上可以告诉mockito你期望在对象上调用哪些函数,以及你期望的结果是什么......非常通用。我希望它能满足您的需求。
关于java - 如何创建假数据和数据对象以进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53364170/