java - Security.Authenticator is not working in Junit test -
i writing junit
test controllers
in javaplay framework
. used spring security
login authentication. here source used reference. everythings working fine until start writing test cases controller. issue unit test shows weird behaviour.
here test file:
@test public void logintestfail(){ result result = invokewithcontext(fakerequest("get","/merchantvisibility"), () -> assetcontroller.merchantvisibilitydemo()); assert.assertequals(303,result.status()); assert.assertequals("/login",result.header("location")); } @test public void logintest(){ map map = new hashmap<>(); map.put("email","abc@xyz.com"); result result = invokewithcontext(fakerequest("get","/merchantvisibility").session(map), () -> assetcontroller.merchantvisibilitydemo()); assert.assertequals(200,result.status()); }
here controller file:
@singleton @security.authenticated(loginauthaction.class) public class assetcontroller extends controller { private static logger.alogger logger = logutil.getlogger(assetcontroller.class); public result merchantvisibilitydemo() { file file = new file(play.current().path().tostring() + "/public/html/merchant_visibility.html"); logger.debug(session().get("email")); return ok((file)); } }
here loginauthaction class :
public class loginauthaction extends security.authenticator { private string session_timeout = "sessiontimeout"; private final configuration configuration; private static logger.alogger logger = logutil.getlogger(loginauthaction.class); @inject public loginauthaction(configuration configuration) { this.configuration = configuration; } @override public string getusername(http.context ctx) { logger.debug(ctx.session().get("email")); //see if user logged in if(ctx.session().get("email") == null){ return null; } // see if session expires string prevtime = ctx.session().get("usertime"); if(prevtime != null && !prevtime.equals("")){ long prevt = long.valueof(prevtime); long currentt = new date().gettime(); long timeout = long.valueof(configuration.getlong(session_timeout))*60*1000; if(currentt - prevt > timeout){ ctx.session().clear(); return null; } } string tickstring = long.tostring(new date().gettime()); ctx.session().put("usertime",tickstring); return ctx.session().get("email"); } @override public result onunauthorized(http.context ctx) { return redirect(controllers.routes.authenticationcontroller.login(ctx.request().path().tostring())); }
this error got :
[error] test controllers.assetcontrollertest.logintestfail failed: expected:<303> was:<200>, took 4.427 sec
the problem code flow not enter loginauthaction
class.
how overcome error ?
when running app in browser flow works fine having problem in testing.
Comments
Post a Comment