Skip to content

Instantly share code, notes, and snippets.

@ossan-pg
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ossan-pg/51c7b0db845242a550ed to your computer and use it in GitHub Desktop.
Save ossan-pg/51c7b0db845242a550ed to your computer and use it in GitHub Desktop.
JMockit を使用して LocalDateTime.now() で指定した日時を取得する.
/*
* 本家(?)のページの方がスマートなのでそっちを見よう.
* http://jmockit.googlecode.com/svn/trunk/samples/fakingXmocking/test/java8testing/Java8SupportTest.java
* mockLocalDateTime() を参照.
*/
package hoge;
import java.time.Clock;
import java.time.LocalDateTime;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
import org.junit.Test;
public class HogeTest {
/**
* LocalDateTime.now() で指定した日時を取得する.
*/
@Test
public void test() {
new MockUp<LocalDateTime>() {
@Mock
public LocalDateTime now(Invocation inv) {
// LocalDateTime.now() は内部で LocalDateTime.now(Clock) を呼び出しているので
// 日の値は 15 になる.
LocalDateTime now = inv.proceed();
return now.withYear(2000).withMonth(1); // .withDayOfMonth(14);
}
@Mock
public LocalDateTime now(Invocation inv, Clock clock) {
LocalDateTime now = inv.proceed(clock);
return now.withYear(2001).withMonth(2).withDayOfMonth(15);
}
};
System.out.println(LocalDateTime.now());
System.out.println(LocalDateTime.now(Clock.systemUTC()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment