Mock class java.time.format.DateTimeFormatter

I am trying to make fun of the DateTimeFormatter class. I have done the following:

@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

}

AwesomeClassuses it for formatting LocalDateTime.now(ZoneId.of("UTC"));. Then the formatted string is used to generate another string. I need to make sure the string is correctly generated. Therefore, I need to return a consistent date either from formatting, or state the static method LocalDateTime.now (..)

What am I doing wrong?

+1
source share
2 answers

An alternative to ridicule LocalDateTime.now()is putting the clock in your class and changing the constructor (or adding another) as follows:

AwesomeClass(DateTimeFormatter fmt, Clock clock) {
  //instead of LocalDateTime now = LocalDateTime.now():
  LocalDateTime now = LocalDateTime.now(clock);
}

Then in your test:

new AwesomeClass(formatter, Clock.fixed(the time you want here));
+4
source

mockito wiki: , !

, ! (, , .)

  • , lib. , , . , , , , , ...
  • , .
  • , . , . , , - .

lib/system, , API, , , .

, , () . DataTimeFormatter , , JDK ( API, JDK).

, , , , , .

wiki , , , , .

+8

All Articles