Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-29 of 29 total

Accessing private methods and fields of a Java class

This class uses reflection to enable you to invoke private methods on a class, or access its private fields. This can be useful for unit testing.

   1  
   2  import java.lang.reflect.Field;
   3  import java.lang.reflect.InvocationTargetException;
   4  import java.lang.reflect.Method;
   5  
   6  import junit.framework.Assert;
   7  
   8  /**
   9   * Provides access to private members in classes.
  10   */
  11  public class PrivateAccessor {
  12  	
  13    public static Object getPrivateField (Object o, String fieldName) {   
  14  	 // Check we have valid arguments... 
  15      Assert.assertNotNull(o);
  16      Assert.assertNotNull(fieldName);
  17      
  18      // Go and find the private field... 
  19      final Field fields[] = o.getClass().getDeclaredFields();
  20      for (int i = 0; i < fields.length; ++i) {
  21        if (fieldName.equals(fields[i].getName())) {
  22          try {
  23            fields[i].setAccessible(true);
  24            return fields[i].get(o);
  25          } 
  26          catch (IllegalAccessException ex) {
  27            Assert.fail ("IllegalAccessException accessing " + fieldName);
  28          }
  29        }
  30      }
  31      Assert.fail ("Field '" + fieldName +"' not found");
  32      return null;
  33    }
  34    
  35    public static Object invokePrivateMethod (Object o, String methodName, Object[] params) {   
  36  		 // Check we have valid arguments... 
  37  	    Assert.assertNotNull(o);
  38  	    Assert.assertNotNull(methodName);
  39  	    Assert.assertNotNull(params);
  40  	    
  41  	    // Go and find the private method... 
  42  	    final Method methods[] = o.getClass().getDeclaredMethods();
  43  	    for (int i = 0; i < methods.length; ++i) {
  44  	      if (methodName.equals(methods[i].getName())) {
  45  	        try {
  46  	          methods[i].setAccessible(true);
  47  	          return methods[i].invoke(o, params);
  48  	        } 
  49  	        catch (IllegalAccessException ex) {
  50  	          Assert.fail ("IllegalAccessException accessing " + methodName);
  51  	        }
  52  	        catch (InvocationTargetException ite) {
  53  	        	Assert.fail ("InvocationTargetException accessing " + methodName);	        	
  54  	        }
  55  	      }
  56  	    }
  57  	    Assert.fail ("Method '" + methodName +"' not found");
  58  	    return null;
  59  	  }  
  60  }

test

// description of your code here

   1  
   2  echo this is a test

Time warp for functional and unit testing


Add this at the top of test/test_helper.rb (or elsewhere if not using rails):

   1  
   2  # Extend the Time class so that we can offset the time that 'now'
   3  # returns.  This should allow us to effectively time warp for functional
   4  # tests that require limits per hour, what not.
   5  class Time #:nodoc:
   6    class <<self
   7      attr_accessor :testing_offset
   8      alias_method :real_now, :now
   9      def now
  10        real_now - testing_offset
  11      end
  12      alias_method :new, :now
  13    end
  14  end
  15  Time.testing_offset = 0


Add this method to Test::Unit::TestCase (in the class definition in test_helper.rb):

   1    # Time warp to the specified time for the duration of the passed block
   2    def pretend_now_is(time)
   3      begin
   4        Time.testing_offset = Time.now - time
   5        yield
   6      ensure
   7        Time.testing_offset = 0
   8      end
   9    end


And now you can write time-based tests. For example:

   1  
   2    def test_should_not_allow_more_than_3_requests_in_last_hour_from_same_ip
   3      (1..3).each { |n| successful_request }
   4  
   5      start_count = WorkOrderRequest.count
   6      post :new, :work_order_request => REQUEST_TEMPLATE
   7      assert_response :redirect
   8      assert_redirected_to :controller => 'work_order_request',
   9                           :action => 'limit_exceeded'
  10      assert_equal start_count, WorkOrderRequest.count
  11    end
  12  
  13    def test_should_not_allow_more_than_10_requests_in_last_24_hours_from_same_ip
  14      10.downto(1) do |n|
  15        pretend_now_is(n.hours.ago) do
  16          successful_request
  17        end
  18      end
  19  
  20      start_count = WorkOrderRequest.count
  21      post :new, :work_order_request => REQUEST_TEMPLATE
  22      assert_response :redirect
  23      assert_redirected_to :controller => 'work_order_request',
  24                           :action => 'limit_exceeded'
  25      assert_equal start_count, WorkOrderRequest.count
  26    end

functional test helper to automate basic CRUD functions

This is a funcitonal test helper, which can be used to create methods on the fly to iterate through your controller methods and test for validations, url parameters and expected responses. It keeps the tests from getting as cluttered.
   1  
   2  #expects a format like this:
   3  	#test_required_attributes_in_controller User,
   4    	#					{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
   5  	#					[:create, :update],
   6  	#					:first_name, :last_name, :username, :email_address, :password
   7  
   8      def test_required_attributes_in_controller( model, options, actions,*required_fields )
   9      	
  10  		sym = model.to_s.downcase.to_sym
  11  		for field in required_fields
  12        		options[:params][sym][field] = ''
  13      	end
  14  		
  15        	actions.each do |action|
  16          	self.class_eval do
  17            		define_method("test_#{action}_method_requires_fields") do
  18              		assert_nothing_raised do
  19  						post action, options[:params],options[:session]
  20  					end
  21              		for field in required_fields
  22        					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
  23      				end
  24      				assert !assigns.empty?,"This method requires specific parameters, yet no errors were created with them missing"
  25            		end
  26          	end
  27        	end
  28  	end
  29  	
  30  	  #Expects format like this: 
  31  	  #   test_required_unique_attributes_in_controller User,
  32  	  #							{:params=>{:id=>1,:user=>{}},:session=>{:user=>{}}},
  33  	  #							[:create, :update],
  34  	  #							:username, :email_address
  35  	  #
  36  		
  37      def test_required_unique_attributes_in_controller( model, options, actions,*required_fields )
  38      	sym = model.to_s.downcase.to_sym
  39  		for field in required_fields
  40        		options[:params][sym][field] = ''
  41      	end
  42  		
  43        	actions.each do |action|
  44          	self.class_eval do
  45            		define_method("test_#{action}_method_requires_unique_fields") do
  46              		assert_nothing_raised do
  47  						post action, options[:params],options[:session]
  48  					end
  49              		for field in required_fields
  50        					assert !assigns(sym).errors[field].empty? unless options[:params][sym][field] == ''
  51      				end
  52      				assert !assigns.empty?,"This method fails without unique parameters, yet no errors were created"
  53            		end
  54          	end
  55        	end
  56      end
  57  	
  58  	#Expects format like this:
  59  	# test_required_url_parameters_in_controller 
  60  	#                                           User,
  61  	#                                           {:params=>{},:session=>{:user=>{}}},
  62  	#                                           :edit, :destroy, :show, :update	
  63  	
  64      def test_required_url_parameters_in_controller(model, options, *actions)
  65        sym = model.to_s.downcase.to_sym
  66        actions.each do |action|
  67          self.class_eval do
  68            define_method("test_#{action}_method_requires_url_parameters") do
  69              post action, options[:params],options[:session]
  70              assert_response :redirect
  71              assert_nil assigns(sym),"This method requires a url parameter, yet the controller still created an object."
  72            end
  73          end
  74        end
  75      end
  76  	
  77    end

Fix for nil object error in Rails test fixtures

If you're seeing errors like this when you run Rails tests:

   1  
   2  # NoMethodError: You have a nil object when you didn't expect it!


You might need to edit test/test_helper.rb to make sure use_instantiated_fixtures is true:

   1  
   2  self.use_instantiated_fixtures = true


Prior to 1.0, Rails automatically created instance variables out of fixtures. So if you had a fixture record named "foo", you could access it in your test as "@foo". As of 1.0, the default is to disable that feature, which breaks a lot of existing code. Mike Clark explains the change.

HitTest //JavaScript Function


With this it's possible to correct the "SELECT over DIV" IE bug as i showed in the example bellow

it checks one element (or an array of them) against another one and returns the itens that matched the hit test (if the element superposes the other one in any place)

[UPDATED CODE AND HELP CAN BE FOUND HERE]


code

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/geral/hittest [v1.0]
   4  
   5  hitTest = function(o, l){
   6  	function getOffset(o){
   7  		for(var r = {l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight};
   8  			o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
   9  		return r.r += r.l, r.b += r.t, r;
  10  	}
  11  	for(var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
  12  		b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
  13  		&& (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
  14  	return j ? !!r.length : r;
  15  };


usage
   1  
   2  <style type="text/css">
   3  #menu{position: absolute; height: 500px; width: 200px; display: none; border: 1px solid #999; background: #eef;}
   4  </style>
   5  
   6  <div id="menu">
   7      <input type="button" onclick="hide();" value="Hide Menu" />
   8  </div>
   9  <form action="">
  10      <fieldset>
  11      <strong>DIV x SELECT</strong>
  12      <br /><select><option>DIV OVER SELECT DIV OVER SELECT DIV OVER SELECT</option></select>
  13      <input type="button" onclick="show();" value="Show Menu" />
  14      </fieldset>
  15  </form>
  16  
  17  
  18  <script type="text/javascript">
  19  //<![CDATA[
  20  
  21  var x = document.getElementById("menu");
  22  
  23  //exemplo de como consertar o problema do select em cima do div, como só acontece no IE, é possível sniffar o browser...
  24  
  25  function show(){
  26      x.style.display = "block";
  27      if(!x.ieFix)
  28          x.ieFix = hitTest(x, document.getElementsByTagName("select"));
  29      for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "hidden");
  30  
  31  }
  32  
  33  function hide(){
  34      x.style.display = "none";
  35      for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "visible");
  36  }
  37  
  38  //]]>
  39  </script>

test

test

Using xpath to test the rails

Originally posted in #rubyonrails by ? springjp

   1  
   2  def test_account_list
   3      #  There should be some accounts to test
   4      assert @ttrueheart.accounts.count > 0
   5   
   6      @request.session[:user] = @ttrueheart
   7      get :list
   8      assert_success
   9   
  10      xml = nil
  11      assert_nothing_thrown { xml = REXML::Document.new(@response.body) }
  12   
  13      @ttrueheart.accounts.each do |account|
  14        td = REXML::XPath.match(xml, "//td[text()=\"#{account.display_string}\"]")
  15        assert_equal(1, td.size)  # Unique entry
  16   
  17        assert_equal(3, REXML::XPath.match(td, 'following-sibling::td/a').size)
  18   
  19        href = REXML::XPath.match(td, "following-sibling::td/a[@href='/account/activity_list/#{account.id}']")
  20        assert_equal(1, href.size)
  21   
  22        href = REXML::XPath.match(td, "following-sibling::td/a[@href='/account/edit/#{account.id}']")
  23        assert_equal(1, href.size)
  24   
  25        href = REXML::XPath.match(td, "following-sibling::td/a[@href='/account/delete/#{account.id}']")
  26        assert_equal(1, href.size)
  27      end
  28    end

test message

   1  function addLoadEvent(func) {
   2    var oldonload = window.onload;
   3    if (typeof window.onload != 'function') {
   4      window.onload = func;
   5    } else {
   6      window.onload = function() {
   7        oldonload();
   8        func();
   9      }
  10    }
  11  }
« Newer Snippets
Older Snippets »
Showing 21-29 of 29 total