静态类和单例模式之间存在什么真实(即实际)差异?
两者都可以在没有实例化的情况下调用,两者都只提供一个"实例",它们都不是线程安全的.还有其他区别吗?
如何模拟集成测试所需的许多依赖项?
我使用Mockito进行"纯粹的"单元测试.在这种情况下,'Pure'意味着测试单个类,模拟它的所有依赖项.美丽.
现在进行集成测试.让我们说在这种情况下,集成测试将测试这样的事情:
我们还要说步骤2中发生的处理是严肃的事情.它依赖于大量的数据库交互,多个外部服务,文件系统,各种各样的东西.流会触发很多副作用,所以我不能简单地确保响应是正确的 - 我需要验证副作用.
这些依赖项中的每一个都由一个无状态服务类包装,这使得它们很好并且可以模拟.
人们如何处理这个?
我很想使用Mockito,这样我就可以验证上述流程会产生的副作用.然而,Mocktio的文档(在很大程度上它的实现)似乎强烈反对在"纯"单元测试之外的上下文中使用它.我试过这条路,但是
编辑
我知道我可以像HSQLDB实例那样处理数据库问题,但仍然存在外部服务的问题.为了重复性,我不能依赖那些服务,处于我需要的状态,等等.我看到的唯一选择是嘲笑它们.
Whatdaya呢?
我需要测试一些遗留代码,它在方法调用中使用单例.测试的目的是确保clas sunder测试调用单例方法.我在SO上看到过类似的问题,但是所有的答案都需要其他依赖项(不同的测试框架) - 我很遗憾只能使用Mockito和JUnit,但这种流行的框架应该是完全可能的.
单身人士:
public class FormatterService {
private static FormatterService INSTANCE;
private FormatterService() {
}
public static FormatterService getInstance() {
if (INSTANCE == null) {
INSTANCE = new FormatterService();
}
return INSTANCE;
}
public String formatTachoIcon() {
return "URL";
}
}
Run Code Online (Sandbox Code Playgroud)
被测试的课程:
public class DriverSnapshotHandler {
public String getImageURL() {
return FormatterService.getInstance().formatTachoIcon();
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
public class TestDriverSnapshotHandler {
private FormatterService formatter;
@Before
public void setUp() {
formatter = mock(FormatterService.class);
when(FormatterService.getInstance()).thenReturn(formatter);
when(formatter.formatTachoIcon()).thenReturn("MockedURL");
}
@Test
public void testFormatterServiceIsCalled() { …Run Code Online (Sandbox Code Playgroud) 我不确定如何模拟枚举单例类.
public enum SingletonObject{
INSTANCE;
private int num;
protected setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
Run Code Online (Sandbox Code Playgroud)
我想在上面的例子中存根getNum(),但我无法弄清楚如何模拟实际的SingletonObject类.我认为使用Powermock准备测试会有所帮助,因为枚举本身就是最终的.
//... rest of test code
@Test
public void test() {
PowerMockito.mock(SingletonObject.class);
when(SingletonObject.INSTANCE.getNum()).thenReturn(1); //does not work
}
Run Code Online (Sandbox Code Playgroud)
这是使用PowerMockMockito 1.4.10和Mockito 1.8.5.