12
Java单测mock new Date()
source link: https://last2win.com/2021/03/28/java-mock-new-date/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Java程序中经常会用到new Date()
来获取当前系统时间,而单测时通常需要指定日期,因为不同时间程序会有不同响应。
普通的Mockito
无法实现mock时间,需要使用JMockit
或者Powermock
JMockit
先添加JMockit
依赖:
testImplementation 'junit:junit:4.13'
testImplementation 'org.jmockit:jmockit:1.49'
使用JMockit
mock 时间:
import java.util.Calendar;
import java.util.Date;
import mockit.Mock;
import mockit.MockUp;
import org.junit.jupiter.api.Test;
import org.springframework.util.Assert;
public class ServingWebContentApplicationTest {
@Test
public void mockTime() {
new MockUp<System>() {
@Mock
public long currentTimeMillis() {
Date fake = new Date(121, Calendar.APRIL, 29);
return fake.getTime();
}
};
Assert.isTrue(new Date().equals(new Date(121, Calendar.APRIL, 29)), "mock time failed");
}
}
Powermock
我在网上找了很多用Powermock
的教程,但每一个方法能用,我这里就不展示了。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK