我需要能够在测试时伪造系统时间。我使用的源码使用了java.time.LocalDate。有没有办法让LocalDate.now()
返回预先设定的日期?
答案 0 :(得分:7)
你有几个选择:
将LocalDate.now()
调用包装在类的非静态方法中。然后你可以模拟该方法来返回你的特定实例 - 如果你在代码中的许多地方直接调用LocalDate.now()
方法,这似乎不太实际。
使用LocalDate.now(Clock)
方法,这非常适合测试,正如评论中已经建议的那样 - 再次修改应用程序代码。
如果可以,请使用Powermockito
。在这种情况下,通过使用mockStatic(Class<?>)
方法模拟静态方法,您可以轻松实现。
第3种方法可以实现为:
@PrepareForTest({ LocalDate.class })
@RunWith(PowerMockRunner.class)
public class DateTest {
@Test
public void yourTest() {
PowerMockito.mockStatic(LocalDate.class);
when(LocalDate.now()).thenReturn(yourLocalDateObj);
}
}
答案 1 :(得分:2)
这里不需要意大利面条代码:保持简单! 编写便利方法并更改其主体以满足您的需求。
public static LocalDate getCurrentTime() {
// You can comment right code to save it during debugging
}
答案 2 :(得分:1)
你能通过代码的构造函数/参数来依赖注入时间吗?
否则,您可以将LocalDate.now()包装在一个静态类中,该类允许您对值进行硬编码以进行测试。
答案 3 :(得分:1)
我通常会建议使用Mockito,但由于该方法是静态的,因此您无法真正模拟该对象。
为什么没有一些&#34; DateProvider&#34;上课为你抓住日期
public class DateProvider{
public LocalDate getNow(){
return LocalDate.now();
}
}
并因此使用它:
new DateProvider().getNow();
这样可以很容易地使用任何LocalDate返回值进行测试
答案 4 :(得分:1)
我正在尝试此页面上的代码,但我注意到我应该首先获取LocalDate实例,然后使用PowerMockito作为下一个代码的2个firstLines
Map<String, Integer> m1 = new LinkedHashMap<>();
m1.put("one", 1);
m1.put("two", 2);
m1.put("three", 3);
Set<Map.Entry<String, Integer>> sme1 = m1.entrySet();
System.out.println(sme1);
sme1.remove(new AbstractMap.SimpleEntry<String, Integer>("one",1));
System.out.println(sme1);
答案 5 :(得分:0)
进行测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class DateTimeFactoryTest {
private static final Logger log = LoggerFactory.getLogger(DateTimeFactoryTest.class);
@MockBean
DateTimeFactory dateTimeFactory;
@Test
public void test001() throws MissingMethodInvocationException {
given(dateTimeFactory.getLocalDate()).willReturn(LocalDate.of(2017,4, 4));
LocalDate ld = dateTimeFactory.getLocalDate();
}
}