我正在尝试模拟DateTimeFormatter类。我已经完成以下工作:
@RunWith(PowerMockRunner.class) @PrepareForTest({DateTimeFormatter.class}) public class UnitTest { private DateTimeFormatter mockDateFormatter; private AwesomeClass awesomeClass; @Before public void setUp() { mockDateFormatter = PowerMockito.mock(DateTimeFormatter.class); awesomeClass = new AwesomeClass(mockDateFormatter); } @Test public void shouldToTestSomethingAwesome() { // Other test code PowerMockito.when(mockDateFormatter.format(any(LocalDate.class))) .thenReturn("20150224"); // Other test code }
AwesomeClass用它格式化LocalDateTime.now(ZoneId.of("UTC"));。然后,格式化的字符串将进一步用于生成另一个字符串。我需要确保正确生成字符串。因此,我需要从格式化程序返回一个一致的日期,或者模拟LocalDateTime.now(..)静态方法
AwesomeClass
LocalDateTime.now(ZoneId.of("UTC"));
我究竟做错了什么?
模拟的替代方法LocalDateTime.now()是将时钟注入您的类并更改您的(或添加另一个)构造函数,如下所示:
LocalDateTime.now()
AwesomeClass(DateTimeFormatter fmt, Clock clock) { //instead of LocalDateTime now = LocalDateTime.now(): LocalDateTime now = LocalDateTime.now(clock); }
然后在您的测试中:
new AwesomeClass(formatter, Clock.fixed(the time you want here));