使用会话数据测试播放控制器

时间:2016-08-25 04:21:01

标签: junit playframework mockito

我有一个简单的控制器测试。

route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));

安全Autheticator看起来像这样:

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);
}

1 个答案:

答案 0 :(得分:1)

您可以阅读this来测试Play控制器,然后按this example进行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
        });
    }
}