Created
January 5, 2017 17:24
-
-
Save masahitojp/d1195217be4bb9106b4f8c4468f3389b to your computer and use it in GitHub Desktop.
Guice to set injector setter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.masahitojp; | |
import com.github.masahitojp.provider.ClockProvider; | |
import com.google.inject.AbstractModule; | |
import com.google.inject.Guice; | |
import com.google.inject.Injector; | |
import org.junit.Before; | |
import org.junit.Test; | |
import java.time.Clock; | |
import java.time.Instant; | |
import java.time.ZoneId; | |
import static org.junit.Assert.*; | |
public class MainTest { | |
Injector injector; | |
@Before | |
public void start() { | |
injector = Guice.createInjector(new AbstractModule(){ | |
@Override | |
protected void configure() { | |
bind(ClockProvider.class).toInstance(new ClockProvider() { | |
private Clock clock = Clock.systemUTC(); | |
@Override | |
public Clock clock() { | |
return clock; | |
} | |
@Override | |
public void set(Clock clock) { | |
this.clock = clock; | |
} | |
@Override | |
public Instant now() { | |
return Instant.now(this.clock()); | |
} | |
}); | |
}}); | |
} | |
@Test | |
public void test() { | |
final Clock test = Clock.fixed(Instant.parse("2007-12-03T10:15:30.00Z"), ZoneId.of("UTC")); | |
injector.getInstance(ClockProvider.class).set(test); | |
TimeService timeService = injector.getInstance(TimeService.class); | |
assertEquals(timeService.now(), test.millis()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment