Showing posts with label JTestR. Show all posts
Showing posts with label JTestR. Show all posts

Wednesday, August 7, 2013

weblog; mockito

Mockito

How to Mock Static Methods

     @Test
     public void testGenerateURL() {
          mockStatic( NetworkUtil.class );

          expect( NetworkUtil.getLocalHostname() ).andReturn( "localhost" );
 
          replayAll();
          String results = generator.generateURL();
          verifyAll();

          assertEquals( 
               "http://localhost/myapplication/images/myimage.gif", 
               results );
     }
http://www.michaelminella.com/testing/how-to-mock-static-methods.html

We have all read it or heard someone talk about it. "Static Methods are Death to Testability"... Something that has become a fundimental piece of the language... is so bad that it must be avoided at all costs in the name of testing. [It's] in the language for a reason and to avoid those uses solely because your toolset doesn't support the testing of it is nonsense. Time to get a new toolset.

http://www.michaelminella.com/testing/how-to-mock-static-methods.html

@PrepareForTest can be declared for the entire class or per test method. As would seem, declarations at the test method level override those at the class level.

org.mockito; Annotation Type Spy

01    public class Test{
02    //Instance for spying is created by calling constructor explicitly:
03    @Spy Foo spyOnFoo = new Foo("argument");
04    //Instance for spying is created by mockito via reflection (only default constructors supported):
05    @Spy Bar spyOnBar;
06    @Before
07    public void init(){
08       MockitoAnnotations.initMocks(this);
09    }
10    ...
11 }
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Spy.html

@Spy requires you to initialize the object being spied; it does not seem to use the default constructor as the documentation indicates.

org.mockito; Class Mockito; documentation

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html

A good place to start learning how to use Mockito. This link supposedly will always return the latest documentation.

How to mock a single method in java

A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);
http://stackoverflow.com/questions/10895605/how-to-mock-a-single-method-in-java

Or, as documented, in some cases you'd need Mockito.doReturn(51).when(aSpy).method1();. – Arjan Sep 13 '12 at 16:23

http://stackoverflow.com/questions/10895605/how-to-mock-a-single-method-in-java

Mockito; doAnswer()

        doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) {
                ... do stuff ...
            }
        }).when(mockBar).create(any(Foo.class));
http://stackoverflow.com/questions/17244499/testing-method-via-spy-with-mocked-collaborators-using-powermock-mockito

This appears to be a way to provide special handling for the associated stub. It reminds me of how blocks are used with RSpec in the Ruby language.

Important gotcha on spying real objects

   List list = new LinkedList();
   List spy = spy(list);
   
   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
   when(spy.get(0)).thenReturn("foo");
   
   //You have to use doReturn() for stubbing
   doReturn("foo").when(spy).get(0);
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

Sometimes it's impossible to use when(Object) for stubbing spies.

http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

Easier mocking with Mockito

http://tutorial.fyicenter.com/out.php?ID=3966

At JTeam we're adopting Mockito in all our new projects. And whenever we have to go back to EasyMock, in the code from earlier projects, we know it was a good move.

http://tutorial.fyicenter.com/out.php?ID=3966

Mockito.LoginServiceExample

package com.om.example.loginservice;
 
import org.junit.Test;
import static org.mockito.Mockito.*;
 
public class LoginServiceTest {
 
   @Test
   public void itShouldSetAccountToLoggedInWhenPasswordMatches() {
      IAccount account = mock(IAccount.class);
      when(account.passwordMatches(anyString())).thenReturn(true);
 
      IAccountRepository accountRepository = mock(IAccountRepository.class);
      when(accountRepository.find(anyString())).thenReturn(account);
 
      LoginService service = new LoginService(accountRepository);
 
      service.login("brett", "password");
 
      verify(account, times(1)).setLoggedIn(true);
   }
}
http://schuchert.wikispaces.com/Mockito.LoginServiceExample http://stackoverflow.com/questions/1404824/learning-resources-for-mockito

This might be a good tutorial to go through; haven't had the time to do so yet. The other link provides references to other tutorials as well.

JUnit and Mockito cooperation

http://fruzenshtein.com/junit-and-mockito/

Mockito framework has conquered my heart. It’s very convenient, its API is clear, usage is laconic."

http://fruzenshtein.com/junit-and-mockito/
ockito framework has conquered my heart. It’s very convenient, its API is clear, usage is laconic."

How to Mock Static Methods

@RunWith( PowerMockRunner.class )
@PrepareForTest( NetworkUtil.class )
public class URLGeneratorTest {
    @Before
     public void setUp() {
          generator = new URLGenerator();
     }

     @Test
     public void testGenerateURL() {
          mockStatic( NetworkUtil.class );

          expect( NetworkUtil.getLocalHostname() ).andReturn( "localhost" );
 
          replayAll();
          String results = generator.generateURL();
          verifyAll();

          assertEquals( 
               "http://localhost/myapplication/images/myimage.gif", 
               results );
     }     
}
http://www.michaelminella.com/testing/how-to-mock-static-methods.html

Mocking static methods (and other "untestable code") is actually quite easy when you put PowerMock to work.

http://www.michaelminella.com/testing/how-to-mock-static-methods.html

Annotation Type PrepareForTest

http://powermock.googlecode.com/svn/docs/powermock-1.3.5/apidocs/org/powermock/core/classloader/annotations/PrepareForTest.html#value%28%29

PrepareForTest() takes either a single class object (e.g., PrepareForTest(MyObject.class) ) or an array of class objects (e.g., PrepareForTest({MyObject.class, AnotherObject.class})

Using PowerMock 1.2.5 with Mockito 1.7

   @PrepareForTest(Static.class); // Static.class contains static methods
   ...

   def testOne{
        //mocks at the class level
        PowerMockito.mockStatic(Static.class);
   }
   ...

   def testTwo{
        //mocks at the time expectations are set up
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
   }
http://code.google.com/p/powermock/wiki/MockitoUsage http://code.google.com/p/powermock/wiki/MockitoUsage13

You can set up mocks at the class level or at the time expectations are set up.

EasyMock

Unit testing with JUnit and EasyMock

     public void testRosyScenario() {
          User results = new User();
          String userName = "testUserName";
          String password = "testPassword";
          String passwordHash = 
               "<md5 hash>";
          expect(mockDao.loadByUsernameAndPassword(eq(userName), eq(passwordHash)))
               .andReturn(results);

          replay(mockDao);
          assertTrue(service.login(userName, password));
          verify(mockDao);
     }
http://www.michaelminella.com/testing/unit-testing-with-junit-and-easymock.html

JRuby and RSpec

RSpec for Java

require 'java'
java_import 'Hello'

describe 'Hello' do
  it 'world' do
    Hello.new.world.should == 'world!'
  end
end
http://ujihisa.blogspot.com/2010/09/rspec-for-java.html

Java has some testing frameworks written in Java, but it's difficult to implement something like RSpec due to the limitation of Java syntax.

http://ujihisa.blogspot.com/2010/09/rspec-for-java.html

JtestR

JtestR bundles an old version of RSpec

Keep this in mind when running the Java runner and when you are using JRuby.

Friday, August 2, 2013

Work notes; unit testing and vim

Redactor

Installing comfortable mexican sofa

https://github.com/comfy/comfortable-mexican-sofa

Rails generator and haml?! I want ERB please!

mvim ~/.rvm/gems/ruby-1.9.3-p194@rails328/gems/comfortable_mexican_sofa-1.8.4/lib/comfortable_mexican_sofa/engine.rb

# comment out 'haml-rails'
# require 'haml-rails'

Of course, when your done generating new code, you will need to enable it again or comfy won't work right.

Integrate a different wysiwyg tool for content editing.

https://github.com/comfy/comfortable-mexican-sofa/issues/321 https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

Not ckeditor, but it should be very similar to this: https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

https://github.com/comfy/comfortable-mexican-sofa/issues/321

Uploading images

http://imperavi.com/redactor/docs/images/ http://guides.rubyonrails.org/form_helpers.html

Vim

Save replace value in vim

let @y = ''

let @z = '/<pre [^>]\+\+><return>'
let @z .= 'v/><return>'
let @z .= '"yy'

normal @z
http://superuser.com/questions/575831/save-replace-value-in-vim

Clear out @y register. Search for desired string, start selecting until specified pattern, and while selection is active, shove it in the @y register ("Yy would append to the @y register).

Formatting columns in a selected block

:%!column -t

"in visual mode
:!column -t

" establish columns by splitting on Tab character
" Ctrl-V, Tab to generate '^I'
:%!column -t -s "^I"
http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

Because my files didn't have a space I had to use :%!column -t -s ','. It removes the commas, so they're not technicaly csv files anymore. But arranges them beautifully, which is what I needed.

http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

To format only the content of the visual block, delimit on :

:!column -t -s '<tab>'

Works like a champ.

Using marks

   ma     set mark a at current cursor location
  'a      jump to line of mark a (first non-blank character in line)
  `a      jump to position (line and column) of mark a 
  :marks  list all the current marks 
http://vim.wikia.com/wiki/Using_marks

Substitute with contents of register or lines range from elsewhere in file in Vim

:%s/foo/\=@a/g
http://stackoverflow.com/questions/662734/substitute-with-contents-of-register-or-lines-range-from-elsewhere-in-file-in-vi

No other replacement values can be included with '\=@a'. Otherwise, it won't work.

Vim - if/elseif/else statements in for loop (command mode)

:for i in range(1,10) | if i > 5 | put =i | endif | endfor
http://stackoverflow.com/questions/6544903/vim-if-elseif-else-statements-in-for-loop-command-mode

Get statement on a single line

While Loops

while c <= 4
  let total += c
  let c += 1
endwhile
http://learnvimscriptthehardway.stevelosh.com/chapters/36.html

Simple enough.

Cool things to do with substitutions

http://vim.wikia.com/wiki/Search_and_replace

How to concatenate

let s .= '%' . i . 'T'
http://stackoverflow.com/questions/4911692/what-does-in-vim-scripts-mean

Like Bash, the spaces are crucially important. Items must be separated by a space on either side.

Wonderful and comprehensive resource!

Other ways to substitute

http://stackoverflow.com/questions/2156405/how-do-i-do-a-g-with-a-concatenating-of-submatches-in-vim

Appending to a register using the capital version of the register letter

    "Kyy
http://stackoverflow.com/questions/1497958/how-to-use-vim-registers

Wow! This stuff is cryptic.

What is 'f' and 'F' and how do they work?

F)vi(
http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

:normal! is something we'll talk about in a later chapter, but for now it's enough to know that it is a command used to simulate pressing keys in normal mode. For example, running :normal! dddd will delete two lines, just like pressing dddd. The at the end of the mapping is what executes the :normal! command.

http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

(f)ind character; (f)next, (F)previous

(vi)select block body delimited by '()', '{}', '<>', or '[]'

Escaping single quotes is easy, but a little verbose

"'" . x . "'"
http://vim.1045645.n5.nabble.com/escape-and-td1200763.html

Remember, the spaces between concatenated strings is important!

Search only over a visual range

/\%Vpattern

<div>hello</div>
http://vim.wikia.com/wiki/Search_only_over_a_visual_range

This saved my skin; the trick is to create a highlighted range, escape, and then use the substitution flag '\%V' to limit substitution to the last selected block. When including a '^' before the flag, it means the first in the selection, not each line in the selection. Interesting...

Getting zen-code to format snippet using multi-line

    let @z = 'gvj<escape>A<return><return><escape>gv<c-y>,div.notes>p*<return>'

A little difficult to see from code snippet, but add a line to the currently selected block, add a couple of new lines after the block, select the last selected block again and then execute the zen-code command.

Ruby; Rails

Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment “\xFF” from ASCII-8BIT to UTF-8

  ...
  File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
    file.write(uploaded_io.read)
  end
http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Try to open the file in binary mode ('wb' instead of 'w')

http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Uploading files

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>
http://guides.rubyonrails.org/form_helpers.html

Html

Pure CSS Blockquote Styling

<blockquote>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae!
<cite>Somebody famous</cite>
</blockquote>
http://www.webmaster-source.com/2012/04/24/pure-css-blockquote-styling/

I'm trying to use this to format quotes in my blog.

Twitter Bootstrap reference (for v2.3.2)

    <div class="row">
    <div class="span4">...</div>
    <div class="span8">...</div>
    </div>
http://getbootstrap.com/2.3.2/scaffolding.html

The new version has some rather significant changes.

CMS

Allow use of ERB in cms

https://github.com/comfy/comfortable-mexican-sofa/issues/67

I have fixed the initializer changing disable_irb=true to allow_irb=false to match the Configuration class definition. My fork is at https://github.com/dsapala/comfortable-mexican-sofa . Feel free to pull commit 6706ff2 for that change.

https://github.com/comfy/comfortable-mexican-sofa/issues/67

Java; Unit Test Mocking

Maven setup for the Mockito API with JUnit

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4-legacy</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
</dependencies>
http://code.google.com/p/powermock/wiki/Mockito_maven

I'm beginning to concede that Mockito is the option most similar to Ruby style mocking.

mockito mock a constructor with parameter

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}
http://stackoverflow.com/questions/13364406/mockito-mock-a-constructor-with-parameter

Mocking constructors requires something extra from just Mockito.

Mocking Static Method

   @PrepareForTest(Static.class); // Static.class contains static methods
        PowerMockito.mockStatic(Static.class);   
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
http://code.google.com/p/powermock/wiki/MockitoUsage

how do I mock Class myVar in Mockito (or PowerMock if needed)?

class FooBar {
  static class Factory {
    static FooBar instance;
    FooBar getInstance() {
      if (instance == null) {
        instance = new FooBar();
      }
      return instance;
    }
  }
  // ...
}
http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There's no good way to use Mockito to replace a function on the Class object itself.

http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Maven configuration for using PowerMockito?

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC8QFjAA&url=http%3A%2F%2Fmvnrepository.com%2Fartifact%2Forg.powermock&ei=PyT8UfTwL8HKiAKxmYHICQ&usg=AFQjCNHKogX9smNHkXFJn6B7xxvH2SHKOA&sig2=8Sn64TLEqcyaFNVx_Lua8w&bvm=bv.50165853,d.cGE

It appears the site was down when I tried to capture data into my blog entry.

Mockito documentation (1.6)

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;
 
 //mock creation
 List mockedList = mock(List.class);
 
 //using mock object
 mockedList.add("one");
 mockedList.clear();
 
 //verification
 verify(mockedList).add("one");
 verify(mockedList).clear();
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

It appears this has a little guide of common uses for Mockito.

Mockito matchers

  //stubbing using anyInt() argument matcher
  when(mockedList.get(anyInt())).thenReturn("element");
  
  //following prints "element"
  System.out.println(mockedList.get(999));
  
  //you can also verify using argument matcher
  verify(mockedList).get(anyInt());
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html

Testing with Mockito - Tutorial

http://www.vogella.com/articles/Mockito/article.html

Fruzenshtein's notes on JUnit and Mockito

    ...  
        @Mock  
        IContainer coffeeContainer;  
        @Mock  
        IContainer waterContainer;  
    ...  
http://fruzenshtein.com/junit-and-mockito/

Mockito - 2 minute tutorial

public class CustomiizeMethodBehaviour  
{  
    public static void main(String[] args)  
    {  
        List myMockedList = mock(List.class);   
        when(myMockedList .get(0)).thenReturn("target");  
          
        System.out.println(myMockedList .get(0));  
    }  
}  
http://www.2min2code.com/articles/mockito_intro/stubbing_method_hardcoded

Mockito documentation (1.9.5)

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#1

Obviously, more comprehensive than the 1.6 version.

JRuby Array to Java Array

{"options"=>["Option One", "Option Two"]}["options"].to_java :string

[1, 2, 3].to_java(:int)
http://stackoverflow.com/questions/1532606/jruby-array-to-java-array

Taming the beast: Using JRuby and RSpec to test a J2EE application

require 'java'
include_class 'org.springframework.context.ApplicationContext'
include_class
  'org.springframework.context.support.ClassPathXmlApplicationContext'
describe "Calculator" do
  it "should add numbers correctly" do
    application_context =
      ClassPathXmlApplicationContext.new "ApplicationContext.xml"
    calculator =  application_context.getBean "calculatorService"
    calculator.sum([1, 2]).should == 3
    calculator.sum([2, 2]).should == 4
    calculator.sum([2, 3, 4]).should == 9
  end
end
http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Working with J2EE applications is something like wandering in a jungle: you never quite know what wild animal you’ll find around the next corner... whatever it is, you’re guaranteed to spend countless hours wasting time learning things you really didn’t want to know.

[Let me] show how you can get your J2EE application under control by using JRuby and RSpec.

http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Mock File class and NullPointerException

java.lang.NullPointerException at java.io.File.(File.java:308)

File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");
http://stackoverflow.com/questions/3515011/mock-file-class-and-nullpointerexception/3515129#3515129

RSpec, JRuby, Mocking, and Multiple Interfaces

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/

The prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/
he prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

The RMock 2.0.0 user guide

http://rmock.sourceforge.net/documentation/xdoc.html

JRuby for the Win

http://winstonyw.com/assets/downloads/JRubyForTheWin.pdf

A PDF document that contains some of the authors notes on JTestR, a product I had hoped would do the job. It appears that it fell off the table awhile back in 2009. Sad, really.

RSpec 1.3.0 Documentation; Configuration

Spec::Runner.configure do |config|
  config.mock_with :rspec, :mocha, :flexmock, or :rr
end
http://rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Runner/Configuration.html

Admittedly, this example is deprecated. See a more recent version of RSpec.

JtestR documentation; Mocking

functional_tests do
  test "that a new HashMap can be created based on another map" do
    map = Map.new

    map.expects(:size).returns(0)

    iter = Iterator.new
    iter.expects(:hasNext).returns(false)

    set = Set.new
    set.expects(:iterator).returns(iter)

    map.expects(:entrySet).returns(set)

    assert_equal 0, HashMap.new(map).size
  end
end
http://jtestr.codehaus.org/Mocks

Only problem is the mocked bindings disappear once execution enters the actual Java code :(

JtestR documentation; Getting Started

http://jtestr.codehaus.org/Getting+Started

Mocking JRuby

  require 'test/unit'
  require 'rubygems'
  require 'mocha'

  ...

    def test_filling_removes_inventory_if_in_stock
      order = OrderImpl.new(TALISKER, 50)
      warehouse = Warehouse.new
      warehouse.stubs(:hasInventory).with(TALISKER, 50).returns(true)
      warehouse.stubs(:remove).with(TALISKER, 50)

      order.fill(warehouse)
      assert order.is_filled
    end  
http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Testing is one of the easy ways to sneak JRuby into your organization because it is easier to write tests in dynamic languages (especially mock object tests) and it isn't code that is deployed, so it eases the minds of the furniture police somewhat.

http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Mocking core Java classes with jmockit

  import mockit.*;
  import java.math.*;

  public class Test {
    public static void main(String[] args) {
      Mockit.redefineMethods(BigDecimal.class, new BigDecimalMock());
      System.err.println(BigDecimal.ONE.add(BigDecimal.ONE));
    }
  }
http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

So, yes, Virginia, it is possible to mock core classes... To make this work practically would likely necessitate launching a separate VM so as to 'scope' the mock to a particular test.

Fugly.

http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

Bash

zen coding multiple elements with children

.br-title>span^.br-content>cfoutput
http://stackoverflow.com/questions/16739994/zen-coding-multiple-elements-with-children

Highlighted block is applied to the last child selector.

Java

Setting the classpath

java -classpath example

java -cp example
http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html

Java Initialize an int array in a constructor

data = new int[]{0, 0, 0};
http://stackoverflow.com/questions/8068470/java-initialize-an-int-array-in-a-constructor

Wednesday, July 31, 2013

Work notes; JTestR, JRuby and JMockit

Java; JMockit

Class MockUp

http://jmockit.googlecode.com/svn/trunk/www/javadoc/mockit/MockUp.html

Introduction to JMockit

public void testDoBusiness() {
Mockit.setUpMocks(MockCustomerDao.class)
List<Customer> customers = service.doBusiness();
http://bwinterberg.blogspot.com/2009/08/unittests-with-jmockit.html

Class Mockit

@Deprecated
public static void setUpMocks(Object... mockClassesOrInstances)
http://jmockit.googlecode.com/svn/trunk/www/javadoc/mockit/Mockit.html#setUpMocks%28java.lang.Object...%29

Instructed to use MockUp instead.

How to mock the default constructor of the Date class with JMockit?

long time = SystemTime.asMillis();
Calendar calendar = SystemTime.asCalendar();
Date date = SystemTime.asDate();
http://stackoverflow.com/questions/4563584/how-to-mock-the-default-constructor-of-the-date-class-with-jmockit

"it's good practice to use a SystemTime abstraction in your java classes. Replace your method calls (System#currentTimeMillis and Calendar#getInstance) and direct construction (new Date()) with static method calls"

Class Mockit; documentation

[[method summary]] http://jmockit.googlecode.com/svn/trunk/www/javadoc/mockit/Mockit.html

It appears that I have been finding lots of documentation that contains deprecated calls. Once I get that code working, I need to find out what the current way of doing business is.

JMockit Quick Tutorial (Cheat sheet)

[[tutorial table of contents]] https://github.com/ajermakovics/eclipse-jmockit-assist/wiki/JMockit-Quick-Tutorial-%28Cheat-sheet%29#wiki-Mocking_static_methods

JMockit and static methods

    @Test
    public void shouldMockStaticMethod() {
        new NonStrictExpectations() {
            final MockitEg mock = null;

            {
                MockitEg.shoeSize();
                result = new MockitEgDelegate();
            }
        };

        assertThat(MockitEg.shoeSize(),
                is(equalTo(MOCK_SHOE_SIZE)));
    }
http://binkley.blogspot.com/2011/07/jmockit-and-static-methods.html

There seems to be many ways of using JMockit. This example might hold some clues to understanding how to mock static methods. Other examples seem to indicate there is no difference between mocking static and instance methods. What happens, however, when there is a method with the same name for both static and instance scopes?

Mocking Static Method Calls

public class SweetLittleMock {
        // Same signature as static method in real class
        public static String doStuff() {
            return "SweetLittleMock";
    }
}
http://www.weblogism.com/item/254/mocking-static-method-calls

Another example of mocking static methods.

jmockit, openJDK and UnsatisfiedLinkError

Try adding <jdk6home>/lib/tools.jar to the classpath, before jmockit.jar. If that doesn't solve the problem, passing -javaagent:jmockit.jar as a JVM initialization parameter definitely should.
http://t5187.codeinpro.us/q/50813bbe4f1eba38a437e655

The problem I was having got resolved when I 1) specified JUnit 4 (instead of 3.x.x) in my pom.xml and 2) installed the Eclipse plugin for JMockit ("JMockit Eclipse Plug-in"; Help > Eclipse Marketplace > Find).

Getting started with the JMockit Testing Toolkit

If you are developing on JDK 1.5, then make sure that -javaagent:jmockit.jar (with the proper absolute or relative path to jmockit.jar) is passed as an initialization parameter to the JVM when running tests. This standard JVM initialization parameter causes it to load on start-up the "Java agent" that JMockit uses internally for bytecode instrumentation; this is required to work in all standard JVMs since version 1.5, in all OSs. You may have to use this parameter even on a newer JDK 1.6+, if its Attach API implementation is not supported by JMockit: such is the case with the IBM J9 JDK 1.6, the Mac OS X JDKs, and with JDKs for the Solaris OS.

If you use TestNG in a JDK 1.6+ environment, JMockit can be initialized in one of three possible ways (apart from use of "-javaagent" indicated above, which can also be used). See this page for details.
http://jmockit.googlecode.com/svn-history/r1166/trunk/www/installation.html

Again, installing the Eclipse plug-in did the trick for me.

mockito; simpler & better mocking

[[mockito logo]] http://code.google.com/p/mockito/

Looks nice and simple, but this being my first time in a long time of unit testing with Java, I don't want to feel like I'm limiting myself.

What's the best mock framework for Java? [closed]

http://stackoverflow.com/questions/22697/whats-the-best-mock-framework-for-java

RDoc

RDoc documentation

  Hyperlinks to the web starting http:, mailto:, ftp:, or www. are recognized. An HTTP url that references an external image file is converted into an inline <IMG..>. Hyperlinks starting 'link:' are assumed to refer to local files whose path is relative to the --op directory.

  Hyperlinks can also be of the form label[url], in which case the label is used in the displayed text, and url is used as the target.
http://rdoc.sourceforge.net/doc/

How to word wrap in Vim

:set textwidth=80
:set wrapmargin=2
http://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns

I also created some useful functions in my .vimrc file:

function! TurnOnLineWrap(...)
  "http://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns
  :set textwidth=80
  :set wrapmargin=2
endfunction

function! TurnOffLineWrap(...)
  "http://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns
  :set textwidth=0
  :set wrapmargin=0
endfunction

Java; JTestR (testing Java with Ruby)

Mocks

JtestR bundles the Ruby mocking framework Mocha. This is the mocking framework used for mocking in both Test/Unit and RSpec tests. For several reasons the RSpec way of mocking doesn't fit well with mocking of Java classes. Mocha on the other hand supports this quite easily.
http://jtestr.codehaus.org/Mocks

'RSpec' example for JTestR

describe Account do
  context "transfering money" do
    it "deposits transfer amount to the other account" do
      source = Account.new(50, :USD)
      target = mock('target account')
      target.should_receive(:deposit).with(Money.new(5, :USD))
      source.transfer(5, :USD).to(target)
    end

    it "reduces its balance by the transfer amount" do
      source = Account.new(50, :USD)
      target = stub('target account')
      source.transfer(5, :USD).to(target)
      source.balance.should == Money.new(45, :USD)
    end
  end
end
https://github.com/olabini/jtestr/tree/master/src/ruby/rspec

I've tried to use pure RSpec; I must be missing something, because I can't seem to get it to work. There doesn't seem to be enough documentation handy for me to understand how to "turn on" RSpec for JTestR.

Configuration

rspec

The rspec configuration works exactly like the test_unit configuration value. It also has the same :all parameter, for specifying that all tests are RSpec tests.
http://jtestr.codehaus.org/Configuration

Supposedly, this is where I configure RSpec to be used for my tests. I get some strange error about the missing method "filenames" when I do.

Getting Started

http://jtestr.codehaus.org/Getting+Started

Versions of JTestR

http://docs.codehaus.org/pages/viewpage.action?pageId=42008590

RSpec documentation for mocks

https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations

How to return a dynamic value from a Mocha mock in Ruby

prc = Proc.new do |xml| 
  "mocked: #{xml}"
end
to_mock.stubs(:post_to_embassy).with(orderInfoXml1).returns(prc.call(orderInfoXml1))
to_mock.stubs(:post_to_embassy).with(orderInfoXml2).returns(prc.call(orderInfoXml2))
http://stackoverflow.com/questions/2742565/how-to-return-a-dynamic-value-from-a-mocha-mock-in-ruby

Mocking constructors in Ruby

require 'mocha'

mock_file_obj = mock("My Mock File") do
  stubs(:some_instance_method).returns("foo")
end

File.stubs(:new).with(is_a(String)).returns(mock_file_obj)
http://stackoverflow.com/questions/72220/mocking-constructors-in-ruby

Mocha documentation - Class: Mocha::Mock

object = mock()
object.expects(:expected_method)
object.expected_method
http://gofreerange.com/mocha/docs/Mocha/Mock.html

Using Java Classes in JRuby

include Java 
...
Dir["/some/path/\*.jar"].each { |jar| require jar }
https://blogs.oracle.com/coolstuff/entry/using_java_classes_in_jruby http://www.pressingquestion.com/720587/Using-Custom-Java-Class-File-In-Jruby

This was instrumental in helping me understand how to pull in Java files into my Ruby tests.

Different dependencies for different build profiles in maven

<profiles>
    <profile>
     <id>debug</id>
     …
     <dependencies>
      <dependency>…</dependency>
     </dependencies>
     …
    </profile>
    <profile>
     <id>release</id>
     …
     <dependencies>
      <dependency>…</dependency>
     </dependencies>
     …
    </profile>
</profiles>
http://stackoverflow.com/questions/166895/different-dependencies-for-different-build-profiles-in-maven

Configure JTestR with Maven

      <plugin>
        <groupId>org.jtestr</groupId>
        <artifactId>jtestr</artifactId>
        <version>0.3.2-SNAPSHOT</version>
        <configuration>
          <port>20333</port>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>test</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
https://github.com/stuarthalloway/jtestr/blob/master/jtestr/examples/multi_maven_project/pom.xml

Anyone using JRuby testing framework for Eclipse/Maven?

http://stackoverflow.com/questions/9179491/anyone-using-jruby-testing-framework-for-eclipse-maven

Cucumber-JVM might be an option I can look into if JTestR doesn't end up working.

JTestR + Eclipse

JRuby & JTestR in Eclipse
 
In your eclipse Package Manager sidebar, Right Click -#> Run As.. -#> Run Configurations. Go ahead and select ‘JUnit’ and hit the ‘New Launch Configuration’ button.
 
Fill in the configuration as follows:
 
* Run a single test
Project: your-project-name
Test class: org.jtestr.ant.JtestRSuite
Now just open the ‘Arguments’ tab and inside the ‘VM arguments:’ box
 
-Djtestr.junit.tests=rspec_tests
rspec_tests is the folder where my tests are stored, feel free to change this to something like /test/jtestr/funny_test or whatever structure you store your files in.
https://gist.github.com/peterlind/660434

Valuable little gem that helped me get my JTestR tests running in Eclipse.

Boost your Java Test with Ruby and JtestR

http://www.infoq.com/news/2008/01/boost-java-test

Yet another plug for JTestR. Again promising the benefits of RSpec. If I could only get it to work for me...

What is needed in order to run the JTestR samples? (or using JTestR at all)

mvn install:install-file -DgroupId=org.jtestr -DartifactId=jruby-complete -Dpackaging=jar -Dversion=r1c672b495cfd204421f4a7aed17f6135e730a3b2 -Dfile=[PATH_TO_DOWNLOADED.jar]
http://stackoverflow.com/questions/5578729/what-is-needed-in-order-to-run-the-jtestr-samples-or-using-jtestr-at-all

I needed to do this as well when I tried to pull in JTestR resources.

JRuby

JRuby documentation

http://jruby.org/documentation

Sweetens up JRuby Mocha with several helpers to simplify testing Java from Ruby

https://github.com/elight/jrsplenda

This is old code. If it could be resurrected, it might prove useful for testing my Java code.

Unit Testing J2EE from JRuby

http://evan.tiggerpalace.com/unit-testing-jruby-from-java-public.pdf

Again, old. And the speaker isn't there to fill in the context. It sounds like it was a great presentation. Might hold some further clues to successfully testing Java using Ruby.

Using JRuby with Maven

    <dependency>
      <groupId>org.jruby</groupId>
      <artifactId>jruby-core</artifactId>
      <version>1.7.0.RC1</version>
    </dependency>
https://github.com/jruby/jruby/wiki/Using-JRuby-with-Maven

JRuby and Java Code Examples

https://github.com/jruby/jruby/wiki/JRubyAndJavaCodeExamples

Ok; looks a little overwhelming at first glance.

Your First Day with JRuby

http://www.jfokus.se/jfokus10/preso/jf-10_FirstDayWithJRuby.pdf

PDF slideshow; without the speaker, I'm not sure how much worth this will be.

RSpec Expectations

http://rubydoc.info/gems/rspec-expectations/frames

Rjb - Ruby Java Bridge

instance = str.new_with_sig('Ljava.lang.String;', 'hiki is a wiki engine')
http://rjb.rubyforge.org/

Another way to call Ruby from Java code?

Module: Mocha::API

 - (Mock) mock(name, &block) 
 - (Mock) mock(expected_methods_vs_return_values = {}, &block) 
 - (Mock) mock(name, expected_methods_vs_return_values = {}, &block) 
http://gofreerange.com/mocha/docs/Mocha/API.html

Class: RSpec::Core::RakeTask

- (Object) pattern

Glob pattern to match files.

default: 'spec/*/_spec.rb'
http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#pattern-instance_method

Trying to get JRSplenda working again by upgrading some of the calls. I admit, I really didn't have enough background on the project yet to do much besides being dangerous.

RSpec

Behaviour Driven Development framework for Ruby (w/tag 1.2.0)

https://github.com/dchelimsky/rspec/tree/1.2.0

What's the require for "RSpec::Core::RakeTask"?

require 'rspec/core/rake_task'
https://www.relishapp.com/rspec/rspec-core/v/2-4/docs/command-line/rake-task

RSpec runner and formatters

https://github.com/rspec/rspec-core

Why can't I load spectask?

no such file to load -- spec/rake/spectask
https://www.ruby-forum.com/topic/312974

In my case, it is because the code I was revamping used RSpec and I had RSpec2 installed.

Ruby

Why does Ruby 1.9.2 remove “.” from LOAD_PATH, and what's the alternative?

require_relative 'file_to_require'

# or
require './filename'

# or 
export RUBYLIB="."

# or
require File.expand_path(File.join(File.dirname(__FILE__), 'filename'))
http://stackoverflow.com/questions/2900370/why-does-ruby-1-9-2-remove-from-load-path-and-whats-the-alternative

Bundler: how to use without rails?

require "rubygems"

# The part that activates bundler in your app:
require "bundler/setup" 

# require your gems as usual
require "some_gem"
http://stackoverflow.com/questions/6999547/bundler-how-to-use-without-rails

Unit testing in Ruby

http://www.developerfusion.com/article/84444/unit-testing-in-ruby/

There is no Java to speak of here, but this looked pretty good for Ruby development.

Maven

Running specific Maven Test with JVM Args

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <forkMode>pertest</forkMode>
          <argLine>${maven.test.jvmargs}</argLine>
        </configuration>
      </plugin>
http://blog.tfd.co.uk/2007/09/21/running-specific-maven-test-with-jvm-args/

Exec Maven Plugin - Usage

Note: The java goal doesn't spawn a new process. Any VM specific option that you want to pass to the executed class must be passed to the Maven VM using the MAVEN_OPTS environment variable. E.g.

MAVEN_OPTS=-Xmx1024m
http://mojo.codehaus.org/exec-maven-plugin/usage.html

Hoe versions

http://rubygems.org/gems/hoe/versions

Trying to get JRSplenda working required some changes. I thought by going back in time to a previous version of Hoe that I would be able to fix somethings. In the end, I think I simply commented out the references to hoe.

Switch from deprecated Hoe.new to Hoe.spec

https://github.com/collectiveidea/migration_test_helper/pull/5

How to use git to download a particular tag?

git clone will give you the whole repository.

After the clone, you can list the tags with git tag -l and then checkout a specific tag: git checkout tags/<tag_name>
http://stackoverflow.com/questions/791959/how-to-use-git-to-download-a-particular-tag

Install Gem from Github Branch?

$ rake build
http://stackoverflow.com/questions/2823492/install-gem-from-github-branch

It's suggested that "gem" be left off the "rake build" command.