2016-08-25 3 views
0

Ich habe einen einfachen Controller-Test.Test Play Controller mit Sitzungsdaten

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

Secured Autheticator sieht wie folgt aus:

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

}

Wie kann ich authService verspotten? Ich habe versucht, mit guice binden zu verspotten, aber diese Methode nicht funktioniert

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

Antwort

1

Sie this zum Testen Play-Controller lesen und folgt this example zum Testen mit Guice.

Für Ihren Fall ist es so etwas wie dieses:

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