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.

No comments:

Post a Comment