我有一个简单的控制器测试。
route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));
安全认证器是这样的:
public class Secured extends play.mvc.Security.Authenticator {
@Inject
AuthServices authService;
public String getUsername(Http.Context context) {
return authService.checkSession(context);
}
@Override
public Result onUnauthorized(Http.Context context) {
return ok(index.render(formFactory.form(forms.LoginForm.class)));
}
}
如何模拟authService
?我试着用guice bind来模拟,但是这个方法不起作用
@Before
public void setup() {
startPlay();
MockitoAnnotations.initMocks(this);
Module testModule = new AbstractModule() {
@Override
public void configure() {
bind(AuthServices.class)
.toInstance(authServices);
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new play.ApplicationLoader.Context(Environment.simple()))
.in(Mode.TEST)
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
}
你可以阅读这篇文章来测试Play控制器,并按照此示例使用Guice进行测试。
对于你的情况是这样的:
public class MyTest extends WithApplication {
@Mock
AuthServices mockAuthService;
@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.overrides(bind(CacheProvider.class).toInstance(mockAuthService))
.in(Mode.TEST)
.build();
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAccounts() {
running(provideApplication(), () -> {
RequestBuilder testRequest = Helpers.fakeRequest(controllers.routes.Accounts.accounts()).session("sessionref","fakeSession");
Result result = route(testRequest);
//assert here the expected result
});
}
}