我写了一个工厂来生产java.sql.Connection物品:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想验证传递给的参数DriverManager.getConnection,但我不知道如何模拟静态方法.我正在使用JUnit 4和Mockito来测试我的测试用例.有没有一种很好的方法来模拟/验证这个特定的用例?
我在这里读了几个关于静态方法的线程,我想我明白了误用/过度使用静态方法会导致的问题.但我并没有真正了解为什么很难模拟静态方法.
我知道其他嘲笑框架,如PowerMock,可以做到这一点,但为什么不能Mockito?
我读过这篇文章,但作者似乎在虔诚地反对这个词static,也许这是我理解不足的原因.
一个简单的解释/链接将是伟大的.
我目前正在使用Mockito来模拟Spring MVC应用程序中的服务层对象,我想在其中测试我的Controller方法.然而,正如我一直在阅读Mockito的具体细节,我发现这些方法doReturn(...).when(...)相当于when(...).thenReturn(...).所以,我的问题是什么是有两个方法,做同样的事情或之间有什么细微的区别点doReturn(...).when(...)和when(...).thenReturn(...)?
任何帮助,将不胜感激.
我有一个A需要经过测试的课程.以下是定义A:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = new DateTime();
//use dateTime to perform some operations
}
}
Run Code Online (Sandbox Code Playgroud)
并且基于该dateTime值,一些数据将被操纵,从数据库中检索.对于此数据库,值通过JSON文件保留.
这使事情复杂化.我需要的dateTime是在测试时将其设置为某个特定日期.有没有办法可以使用mockito模拟局部变量的值?
我正在为一个FizzConfigurator看起来像这样的类编写单元测试:
public class FizzConfigurator {
public void doFoo(String msg) {
doWidget(msg, Config.ALWAYS);
}
public void doBar(String msg) {
doWidget(msg, Config.NEVER);
}
public void doBuzz(String msg) {
doWidget(msg, Config.SOMETIMES);
}
public void doWidget(String msg, Config cfg) {
// Does a bunch of stuff and hits a database.
}
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个简单的单元测试来存储doWidget(String,Config)方法(这样它实际上不会触发并命中数据库),但这可以让我验证调用doBuzz(String)最终会执行doWidget.Mockito似乎是这里工作的合适工具.
public class FizzConfiguratorTest {
@Test
public void callingDoBuzzAlsoCallsDoWidget() {
FizzConfigurator fixture = Mockito.spy(new FizzConfigurator());
Mockito.when(fixture.doWidget(Mockito.anyString(), Config.ALWAYS)).
thenThrow(new RuntimeException());
try {
fixture.doBuzz("This …Run Code Online (Sandbox Code Playgroud)