Jor*_*.S. 37 java junit unit-testing mocking mockito
我有一个使用当前时间进行一些计算的函数.我想用mockito嘲笑它.
我要测试的类的一个例子:
public class ClassToTest {
public long getDoubleTime(){
return new Date().getTime()*2;
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这样的东西:
@Test
public void testDoubleTime(){
mockDateSomeHow(Date.class).when(getTime()).return(30);
assertEquals(60,new ClassToTest().getDoubleTime());
}
Run Code Online (Sandbox Code Playgroud)
有可能嘲笑吗?我不想更改"经过测试"的代码以便进行测试.
mun*_*ngm 51
正确的做法是重新构建代码,使其更易于测试,如下所示.重构代码以删除对Date的直接依赖将允许您为正常运行时和测试运行时注入不同的实现:
interface DateTime {
Date getDate();
}
class DateTimeImpl implements DateTime {
@Override
public Date getDate() {
return new Date();
}
}
class MyClass {
private final DateTime dateTime;
// inject your Mock DateTime when testing other wise inject DateTimeImpl
public MyClass(final DateTime dateTime) {
this.dateTime = dateTime;
}
public long getDoubleTime(){
return dateTime.getDate().getTime()*2;
}
}
public class MyClassTest {
private MyClass myClassTest;
@Before
public void setUp() {
final Date date = Mockito.mock(Date.class);
Mockito.when(date.getTime()).thenReturn(30L);
final DateTime dt = Mockito.mock(DateTime.class);
Mockito.when(dt.getDate()).thenReturn(date);
myClassTest = new MyClass(dt);
}
@Test
public void someTest() {
final long doubleTime = myClassTest.getDoubleTime();
assertEquals(60, doubleTime);
}
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ora 21
如果你有遗留的代码,你不能重构,你不想影响System.currentTimeMillis(),请尝试使用Powermock和PowerMockito
//note the static import
import static org.powermock.api.mockito.PowerMockito.whenNew;
@PrepareForTest({ LegacyClassA.class, LegacyClassB.class })
@Before
public void setUp() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
Date NOW = sdf.parse("2015-05-23 00:00:00");
// everytime we call new Date() inside a method of any class
// declared in @PrepareForTest we will get the NOW instance
whenNew(Date.class).withNoArguments().thenReturn(NOW);
}
public class LegacyClassA {
public Date getSomeDate() {
return new Date(); //returns NOW
}
}
Run Code Online (Sandbox Code Playgroud)
你可以通过使用PowerMock 来实现这一点,它可以增强Mockito能够模拟静态方法.然后你可以模拟System.currentTimeMillis(),这是new Date()最终得到时间的地方.
你可以.我不会就你是否应该提出意见.