程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java中設置session超時(掉效)的三種辦法

Java中設置session超時(掉效)的三種辦法

編輯:關於JAVA

Java中設置session超時(掉效)的三種辦法。本站提示廣大學習愛好者:(Java中設置session超時(掉效)的三種辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中設置session超時(掉效)的三種辦法正文



在筆者開辟的體系中,有年夜量的數據須要剖析,不只請求數據剖析精確,並且對速度也有必定的請求的。沒有寫測試代碼之前,筆者用幾個很年夜的辦法來完成這類需求。成果可想而知,代碼復雜,保護艱苦,難於擴大。借營業調劑的機遇,筆者痛定思痛,決議從測試代碼做起,並跟著赓續地進修和運用,漸漸領會到測試代碼的利益。

  •     轉變思緒:能做到從需求到代碼的進程轉換,慢慢細化;
  •     簡化代碼:力爭讓每一個辦法都很小,只專注一件事;
  •     優化代碼:當測試代碼寫不出來,或許須要寫很長的時刻,解釋代碼是有成績的,是可以被分化的,須要進一步優化;
  •     便於擴大:當擴大新營業或修正舊營業時,假如測試代碼沒有勝利,則解釋擴大和修正不勝利;
  •     時半功倍:貌似寫測試代碼很費時,現實在測試、安排和後續擴大中,測試代碼將節儉更多的時光。

情況搭建

筆者采取的測試情況是比擬風行通用的框架:RSpec + Factory Girl,並用autotest主動對象。RSpec是一種描寫性說話,經由過程可行的例子描寫體系行動,異常輕易上手,測試用例異常輕易懂得。Factory Girl可以很好的贊助結構測試數據,免除了本身寫fixture的懊惱。Autotest能主動運轉測試代碼,隨時檢測測試代碼的成果,而且有許多的插件支撐,可讓測試成果顯示的很炫。
第一步 裝置rspec和rspec-rails

在敕令行中履行以下敕令:

$ sudo gem install rspec v = 1.3.0
$ sudo gem install rspec-rails v = 1.3.2

裝置完成後,進入rails運用地點的目次,運轉以下劇本,生成spec測試框架:

$ script/generate rspec     
  exists lib/tasks
 identical lib/tasks/rspec.rake
 identical script/autospec
 identical script/spec
  exists spec
 identical spec/rcov.opts
 identical spec/spec.opts
 identical spec/spec_helper.rb

第二步 裝置factory-girl


在敕令行中履行以下敕令:

$ sudo gem install rspec v = 1.3.0
$ sudo gem install rspec-rails v = 1.3.2

裝置完成後,進入rails運用地點的目次,運轉以下劇本,生成spec測試框架:

$ script/generate rspec     
  exists lib/tasks
 identical lib/tasks/rspec.rake
 identical script/autospec
 identical script/spec
  exists spec
 identical spec/rcov.opts
 identical spec/spec.opts
 identical spec/spec_helper.rb

第二步 裝置factory-girl

在敕令行中履行以下敕令:

$ sudo gem install factory-girl

在config/environment/test.rb中,參加factory-girl這個gem:

config.gem "factory_girl"

在spec/目次下,增長一個factories.rb的文件,用於一切事後界說的model工場。
第三步 裝置autotest

在敕令行中履行以下敕令:

$ sudo gem install ZenTest
$ sudo gem install autotest-rails

然後設置與RSpec的集成,在rails運用的目次下,運轉以下的敕令,便可以顯示測試用例的運轉成果。

RSPEC=true autotest or autospec

在本身的home目次下,增長一個.autotest設置一切的Rails運用的autotest插件。固然,也能夠把這個文件加到每一個運用的根目次下,這個文件將籠罩home目次下的文件設置。autotest的插件許多,筆者用到以下的plugin:

$ sudo gem install autotest-growl
$ sudo gem install autotest-fsevent
$ sudo gem install redgreen

設置.autotest文件,在.autotest中,參加以下代碼。

require 'autotest/growl' 
require 'autotest/fsevent' 
require 'redgreen/autotest' 

Autotest.add_hook :initialize do |autotest|
 %w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|
  autotest.add_exception(exception)
 end
end

測試經歷

裝置了需要的法式庫今後,便可以寫測試代碼了。本例中,一切運用都是在Rails 2.3.4上開辟的,RSpec采取的是1.3.0的版本。為了很好的解釋成績,我們假定如許的需求:斷定一個用戶在一個時光段內能否遲到。寫測試代碼時都是遵守一個准繩,只關懷輸出和輸入,詳細的完成其實不在測試代碼的斟酌規模以內,是行動驅動開辟。依據這個需求,我們將會設計辦法absence_at(start_time,end_time),有兩個輸出值start_time和end_time和一個輸入值,類型是boolean。對應的測試代碼以下:

describe "User absence or not during [start_time,end_time]" do
 before :each do 
  @user = Factory(:user)
 end

 it "should return false when user not absence " do
  start_time = Time.utc(2010,11,9,12,0,0,0)
  end_time = Time.utc(2010,11,9,12,30,0) 
  @user.absence_at(start_time,end_time).should be_false
 end

 it "should return true when user absence " do
  start_time = Time.utc(2010,11,9,13,0,0,0)
  end_time = Time.utc(2010,11,9,13,30,0) 
  @user.absence_at(start_time,end_time).should be_ture
 end
end

測試代碼曾經完成。至於absence_at辦法我們其實不關懷它的完成,只需這個辦法的成果能讓測試代碼運轉成果准確便可以。在此測試代碼的基本上,便可以年夜膽地去完成代碼,並依據測試代碼的成果赓續修正代碼直到一切測試用例經由過程。
Stub的應用

寫測試代碼,最好起首從model開端。由於model的辦法能很好與輸出輸入的准繩吻合,輕易上手。最後的時刻,你會發明mock和stub很好用,任何的對象都可以mock,而且在它的基本上可以stub一些辦法,省去結構數據的費事,一度讓筆者認為測試代碼是如斯俏麗,一步步的深刻,才發明本身墮入了stub的誤區。照樣援用下面的例子,我們的代碼完成以下:

class User < ActiveRecord::Base
 def absence_at(start_time,end_time)  
  return false if have_connection_or_review?(start_time,end_time)
  return (login_absence_at?(start_time,end_time) ? true : false)  
 end
end

依照最後寫測試代碼的思緒,本辦法中存在三種情形,即須要三個用例,並且還挪用了其他兩個辦法,須要對他們停止stub,因而就有了上面的測試代碼。記適合時完成後還很高興,心中還想:這麼寫測試代碼真風趣。

before(:each) do
 @user = User.new
end

describe "method <absence_at(start_time,end_time)>" do 
 s = Time.now
 e = s + 30.minutes
 # example one
 it "should be false when user have interaction or review" do
  @user.stub!(:have_connection_or_review?).with(s,e).and_return(true)
  @user.absence_at(s,e).should be_false
 end
  
 # example two
 it "should be true when user has no interaction and he no waiting at platform" do
  @user.stub!(:have_connection_or_review?).with(s,e).and_return(false)
  @user.stub!(:login_absence_at?).with(s,e).and_return(true)
  @user.absence_at(s,e).should be_true
 end

 # example three
 it "should be false when user has no interaction and he waiting at platform" do
  @user.stub!(:have_connection_or_review?).with(s,e).and_return(false)
  @user.stub!(:login_absence_at?).with(s,e).and_return(false)
  @user.absence_at(s,e).should be_false
 end  
end

下面的測試代碼,是典范把代碼的完成細節帶到了測試代碼中,完整是捨本逐末的。固然這個測試代碼運轉的時刻,成果都是准確的。那是由於用stub來假定一切的子辦法都是對的,然則假如這個子辦法have_connection_or_review?產生變更,它不前往boolean值,那末將會產生甚麼呢?這個測試代碼仍然准確,恐怖吧!這都沒有起到測試代碼的感化。

別的,假如是如許,我們不只要修正have_connection_or_review?的測試代碼,並且還要修正absence_at的測試代碼。這不是在增年夜代碼保護量嗎?

比擬而言,不消stub的測試代碼,不消修正,假如Factory的數據沒有產生變更,那末測試代碼的成果將是毛病的,由於have_connection_or_review?沒有經由過程測試,招致absence_at辦法沒法正常運轉。

其實stub重要是mock一些本辦法或許本運用中沒法獲得的對象,好比在tech_finish?辦法中,挪用了一個file_service來取得Record對象的一切文件,在本辦法測試代碼運轉進程中,沒法獲得這個service,這時候stub就起感化了:

class A < ActiveRecord::Base
 has_many :records
 def tech_finish?
  self.records.each do |v_a|
   return true if v_a.files.size == 5
  end
  return false
 end
end

class Record < ActiveRecord::Base
 belongs_to :a
 has_files # here is a service in gem
end

所對應的測試代碼以下:

describe "tech_finish?" do
 it "should return true when A's records have five files" do
  record = Factory(:record)
  app = Factory(:a,:records=>[record])
  record.stub!(:files).and_return([1,2,3,4,5])   
  app.tech_finish?.should == true
 end

 it "should return false when A's records have less five files" do
  record = Factory(:record)
  app = Factory(:a,:records=>[record])
  record.stub!(:files).and_return([1,2,3,5])   
  app.tech_finish?.should == false
 end
end

Factory的應用

有了這個工場,可以很便利的結構分歧的模仿數據來運轉測試代碼。照樣下面的例子,假如要測試absence_at辦法,觸及到多個model:

  •     HistoryRecord:User的上課記載
  •     Calendar:User的課程表
  •     Logging:User的日記信息

假如不消factory-girl結構測試數據,我們將不能不在fixture結構這些測試數據。在fixture結構的數據沒法指定是誰人測試用例應用,然則假如用Factory的話,可認為這個辦法專門指定一組測試數據。

Factory.define :user_absence_example,:class => User do |user|
 user.login "test"
 class << user
  def default_history_records
   [Factory.build(:history_record,:started_at=>Time.now),
    Factory.build(:history_record,:started_at=>Time.now)]
  end
  def default_calendars
   [Factory.build(:calendar),
    Factory.build(:calendar)]      
   end
   def default_loggings
   [Factory.build(:logging,:started_at=>1.days.ago),
    Factory.build(:logging,:started_at=>1.days.ago)]
   end
  end
  user.history_records {default_history_records}
  user.calendars {default_calendars}
  user.loggings {default_loggings}
end

這個測試數據的結構工場,可以放在factories.rb文件中,便利其他測試用例應用,也能夠直接放到測試文件的before中,僅供本測試文件應用。經由過程factory的結構,不只可認為多個測試用例同享統一組測試數據,並且測試代碼也簡練清楚明了。

before :each do
 @user = Factory.create(:user_absence_example)
end

Readonly的測試

在筆者的體系中,年夜量應用了acts_as_readonly,從別的一個數據庫來讀取數據。因為這些model其實不在本體系中,所以當用Factory結構測試數據的時刻,總會有成績。固然也能夠應用mock來到達這個目標,然則因為mock的局限性,照樣沒法靈巧的知足結構測試數據的須要。為此,擴大了一些代碼,使得這些model仍然可以測試。焦點思惟則是,依據設置裝備擺設文件的設置,將對應的readonly的表創立在測試數據庫,這個操作在運轉測試之前履行,如許就到達與其他model一樣的後果。site_config設置裝備擺設文件中,關於readonly的設置裝備擺設格局以下:

readonly_for_test:
 logings:
  datetime: created_at
  string: status
  integer: trainer_id

Gem的測試

Gem在Rails中被普遍應用,並且是最基本的器械,是以它的精確無誤就顯得加倍主要。在赓續理論的基本上,筆者地點的團隊總結出一種用spec測試gem的辦法。假定我們要測試的gem是platform_base,步調以下:

1. 在gem的根目次下創立一個目次spec(途徑為platform_base/spec)。

2. 在gem的根目次下創立文件Rakefile(途徑為platform_base/Rakefile),內容以下:

require 'rubygems'
require 'rake'

require 'spec/rake/spectask'

Spec::Rake::SpecTask.new('spec') do |t|
 t.spec_opts = ['--options', "spec/spec.opts"]
 t.spec_files = FileList['spec/**/*_spec.rb']
end

3. 文件在spec目次下創立spec.opts(途徑為platform_base/spec/spec.opts),內容以下:

--colour
--format progress
--loadby mtime
--reverse

4. 在spec目次下,創立一個Rails app,名為test_app。這個新運用須要有spec目次和spec_helper.rb文件。

5. 為了堅持簡化,把這個新app(test_app)整頓一下,刪除vendor和public目次,終究的構造以下:

test_app
   |- app
   |- config
   |   |- environments
   |   |- initializers
   |   |- app_config.yml
   |   |- boot.rb
   |   |- database.yml
   |   |- environment.rb
   |   \- routes.rb
   |- db
   |   \- test.sqlite3
   |- log
   \- spec
       \- spec_helper.rb

6. 在config/environment.rb設置裝備擺設文件中,增長以下代碼:

Rails::Initializer.run do |config|
 config.gem 'rails_platform_base'
end

7. 在platform_base/spec/目次下增長helpers_spec.rb文件,內容以下:

require File.join(File.dirname(__FILE__), 'test_app/spec/spec_helper')

describe "helpers" do
 describe "url_of" do
  before do
   Rails.stub!(:env).and_return("development")
   @controller = ActionController::Base.new
  end

  it "should get url from app's configration" do
   @controller.url_of(:article, :comments, :article_id => 1).should == "http://www.idapted.com/article/articles/1/comments"
   @controller.url_of(:article, :comments, :article_id => 1, :params=>{:category=>"good"}).should == "http://www.idapted.com/article/articles/1/comments?category=good"
  end
 end
end

至此,預備任務曾經停當,可以在platform_base目次下,運轉rake spec來停止測試,固然如今甚麼都不會產生,由於還沒有測試代碼呢。本辦法中,最症結的就是上面的require語句,不只加載了Rails environment,並且把gem在test_app中應用並測試。

require File.join(File.dirname(__FILE__), 'test_app/spec/spec_helper')

Controller的測試

關於controller的測試,普通來講比擬簡略,根本是三段式:初始化參數、要求辦法、前往render或許redirect_to。以下例中,對某個controller的index辦法的測試:

describe "index action" do
 it "should render report page with the current month report" do
  controller.stub!(:current_user).and_return(@user)
  get :index,{:flag => “test”}
  response.should render_template("index")
 end
end

有些controller會設置session或許flash,這時候的測試代碼就必定要檢討這個值設置的能否准確,並且還須要增長測試用例來籠罩分歧的值,如許能力對辦法停止周全的測試。以下例:

describe "create action" do
 it "should donot create new user with wrong params" do
  post :create
  response.should redirect_to(users_path)
  flash[:notice].should == "Create Fail!"
 end

 it "should create a new user with right params" do
  post :create, {:email => "[email protected]"}
  response.should redirect_to(users_path)
  flash[:notice].should == "Create Successful!"
 end
end

同時,也須要對controller的assigns停止測試,以包管前往准確的數據。以下例:

before(:each) do
 @course = Factory(:course)
end 

describe "show action" do
 it "should render show page when flag != assess and success" do 
  get :show, :id => @course.id, :flag =>"test"
  response.should render_template("show")
  assigns[:test_paper].should == @course
  assigns[:flag].should == "test"
 end

 it "should render show page when flag == assess and success" do
  get :show, :id => @course.id, :flag =>"assess"
  response.should render_template("show")
  assigns[:test_paper].should == @course
  assigns[:flag].should == "assess"
 end  
end

View的測試

View的測試代碼寫的比擬少,根本上是把焦點的view部門集成到controller中來測試。重要用integrate_views辦法。以下例:

describe AccountsController do
 integrate_views
 describe "index action" do
  it "should render index.rhtml" do
   get :index
   response.should render_template("index")
   response.should have_tag("a[href=?]",new_account_path)
   response.should have_tag("a[href=?]",new_session_path)
  end
 end
end

總結瞻望

在寫測試代碼的時刻,其實不必定要事無大小,有些比擬簡略的辦法和Rails的外部的辦法,如named_scope,就完整沒有需要測試。本文中,只引見了用rspec寫單位測試的代碼,關於集成測試沒有觸及,這也是往後盡力的一個偏向。

別的,用cumumber + rspec + webrat的BDD開辟形式也是相當不錯的。特別是cumumber對需求的描寫,完整可以用它來做需求剖析。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved