我正在为junit
中的controllers
撰写JavaPlay framework
测试。我使用Spring Security
进行登录验证。 Here是我用来参考的来源。 Everythings工作正常,直到我开始为控制器编写测试用例。问题是单元测试显示出奇怪的行为。
这是测试文件:
@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());
}
这是控制器文件:
@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));
}
}
这是LoginAuthAction类:
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 is 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()));
}
这是我得到的错误:
[error] Test controllers.AssetControllerTest.loginTestFail failed: expected:<303> but was:<200>, took 4.427 sec
问题是代码流没有进入LoginAuthAction
类。
如何克服此错误?
当我在浏览器中运行应用程序时,流程正常但在测试中遇到此问题。