[unit test] how to test real-time based method. (for example new Date() )

While we are writing the unit test cases, we may meet some method that is real-time based. It'll be a challenge to get the expected result as they are changing with time, then it's time to use the Mock tool.

today I meet the same issue, I need to test one method timeFormat(), this method is to format the current time with the formate provided, such as "yyyyMMddhhmmss", the result for current time should be "20130530041043". It takes me long time to solve the real-time issue, because the timeFormat() will always call new Date(), but I cannot handle the result obviously. What I am interested is whether the method can format the time with the given time. Then the "Power Mock" gave me a big help, the following is my resolution:

the businees code is :

import java.text.SimpleDateFormat;
import java.util.Date;

public class Timer {
public String timeFormat(){
String format = "yyyyMMddhhmmss";
SimpleDateFormat dateFm = new SimpleDateFormat(format);
Date date = new Date();
long t = date.getTime();
String dateTime = dateFm.format(new Date(t));
return dateTime;
}
...//other businees code
}


of course, if every time I call new Date(), and it return with a fixed value, it will be very easy to test this method. OK, this is the point we need to face. With PowerMock, we can resolve it very easily.



@RunWith(PowerMockRunner.class)
@PrepareForTest({Timer.class})
public class TimerTest {
Timer timer;
@Before
public void init() throws Exception{
timer = new Timer();
}
@Test
public void testTimeFormat () throws Exception{
long simulatedTime = 1369897050940l;//This the simulated value we used.
String expectResult = "20130530033718";//simulated.
Date date = PowerMock.createMock(Date.class);
expectNew(Date.class).andReturn(date);
expect(date.getTime()).andReturn(simulatedTime);
// we hope the new Date() will return with the date we have defined //before. (which means the new Date() will be a fixed value)
// we need to simulate getTime() method because the format() method will call it.
PowerMock.replay(date,Date.class);
String actualResult = timer.timeFormat();
assertEquals(expectResult,actualResult);

}
}



I have added the detail comments in the code. In this way, we can simulate the Object new Date() with any value.

you can refer to this page to have a detail knowledge about powermock:
http://www.ibm.com/developerworks/cn/java/j-lo-powermock/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值