Tag Archives: Java

More on JMock and TestNG

More on JMock and TestNG
Firstly, I would like to provide a small fix to the code provided in the previous entry: JMock for TestNG (or JUnit-free JMock)

/**
* Verify the expected behavior for the mocks registered by the current thread and
* also releases them.
*/
public static synchronized void verifyAndRelease() {
   Thread currentThread= Thread.currentThread();
   List mocks = s_mockObjects.get(currentThread);
   if(null != mocks) {
       try {
           for(Verifiable verifiable : mocks) {
               verifiable.verify();
           }
       finally {
           // make sure the mocks are released
           mocks.clear();
           s_mockObjects.put(currentThread, null);
       }
   }
}

The fix assures that even if the verification of a mock fails, the current mocks are released and will not remain around till the next test.

I have started to completely free JMock of its JUnit “addiction”. I have found three types of dependencies:

  • classes in the hierarchy of org.junit.TestCase (3). These can be completely replaced by the class I have already posted
  • usage of org.junit.AssertionFailureException. Having in mind that TestNG works for JVM 1.4+, we have directly used the java.lang.AssertError, and I am thinking to do the same here
  • a couple of classes extending org.junit.Assert (even if they aren’t using much of it). Considering that TestNG propose a more readable form for assertions through org.testng.Assert, this change is quite trivial

I can confess that these changes are already available on my machine and I am already using them. Me and Joe have been discussing about the possibility to integrate these changes directly in JMock. If this will not happen, than I will most probably include the code in TestNG.

A last point (one that I just get me burnt tonite), is that JMock doesn’t check (or I haven’t figured how to make it) the order of expectations, so from its perspective the following code is same correct (or wrong):

   [...]
   mock.expect(once()).method("methodOne");
   mock.expect(once()).methog("methodTwo");
   [...]
   mock.verify();

and

   [...]
   mock.expect(once()).method("methodTwo");
   mock.expect(once()).methog("methodOne");
   [...]
   mock.verify();

will both pass or fail disregarding the real order of invocation. I agree that in most of the cases, JMock behavior is enough good, but not having a way to force the order of invocation is in my opinion a missing feature. I am gonna try to add this feature to my code.

Advertisement

2 Comments

Filed under Uncategorized

JMock for TestNG (or JUnit-free JMock)

JMock for TestNG
Last days I have created a small utility class that would allow me to work with JMock without depending on JUnit. If you develop tests using TestNG and you need mocks a la JMock, than here it is (I have removed the imports so that the listing doesn’t go too long):

/**
 * An utility class to allow static usage of JMock (removes the restriction
 * to subclass JMock specific classes).
 * 
 * @author Alexandru Popescu
 */
public class JMock {
    static final Constraint ANYTHING = new IsAnything();
    private static final WeakHashMap<Thread, List<Verifiable>> s_mockObjects = 
            new WeakHashMap<Thread, List<Verifiable>>();
    
    /**
     * Creates a mock object that mocks the given type.  
     * The mock object is named after the type;  the exact
     * name is calculated by {@link #defaultMockNameForType}.
     *
     * @param mockedType The type to be mocked.
     * @return A {@link Mock} object that mocks <var>mockedType</var>.
     */
    public static Mock mock(Class mockedType) {
        return mock(mockedType, defaultMockNameForType(mockedType));
    }

    /**
     * Creates a mock object that mocks the given type and is explicitly given a name.
     * The mock object is named after the type;  
     * the exact name is calculated by {@link #defaultMockNameForType}.
     *
     * @param mockedType The type to be mocked.
     * @param roleName The name of the mock object
     * @return A {@link Mock} object that mocks <var>mockedType</var>.
     */
    public static Mock mock( Class mockedType, String roleName ) {
        Mock newMock = new Mock(newCoreMock(mockedType, roleName));
        registerToVerify(newMock);
        return newMock;
    }
    
    public static Mock mock(Class mockedClass, 
                            String roleName, 
                            Class[] constructorArgumentTypes, 
                            Object[] constructorArguments) {
        Mock newMock = new Mock(newClassCoreMock(mockedClass, 
                                                 roleName, 
                                                 constructorArgumentTypes, 
                                                 constructorArguments));
        registerToVerify(newMock);
        return newMock;
    }

    public static Mock mock(Class mockedClass, 
                            Class[] constructorArgumentTypes, 
                            Object[] constructorArguments) {
        return mock(mockedClass, 
                    defaultMockNameForType(mockedClass), 
                    constructorArgumentTypes, 
                    constructorArguments);
    }

    public static Stub returnValue(Object o) {
        return new ReturnStub(o);
    }

    public static Stub returnValue(boolean result ) {
        return returnValue(new Boolean(result));
    }

    public static Stub returnValue(byte result ) {
        return returnValue(new Byte(result));
    }

    public static Stub returnValue(char result ) {
        return returnValue(new Character(result));
    }

    public static Stub returnValue(short result ) {
        return returnValue(new Short(result));
    }

    public static Stub returnValue(int result ) {
        return returnValue(new Integer(result));
    }

    public static Stub returnValue(long result ) {
        return returnValue(new Long(result));
    }

    public static Stub returnValue(float result ) {
        return returnValue(new Float(result));
    }

    public static Stub returnValue(double result ) {
        return returnValue(new Double(result));
    }

    public static Stub returnIterator(Collection collection) {
        return new ReturnIteratorStub(collection);
    }
    
    public static Stub returnIterator(Object[] array) {
        return new ReturnIteratorStub(array);
    }
    
    public static Stub throwException(Throwable throwable) {
        return new ThrowStub(throwable);
    }

    public static InvocationMatcher once() {
        return new InvokeOnceMatcher();
    }

    public static InvocationMatcher atLeastOnce() {
        return new InvokeAtLeastOnceMatcher();
    }

    public static InvocationMatcher exactly(int expectedCount) {
        return new InvokeCountMatcher(expectedCount);
    }
    
    public static InvocationMatcher never() {
        return new TestFailureMatcher("not expected");
    }

    public static InvocationMatcher never( String errorMessage ) {
        return new TestFailureMatcher("not expected ("+errorMessage+")");
    }
    
    public static Stub onConsecutiveCalls(Stub... stubs) {
        return new StubSequence(stubs);
    }
    
    public static Stub doAll(Stub... stubs) {
        return new DoAllStub(stubs);
    }
    
    public static IsEqual eq(Object operand) {
        return new IsEqual(operand);
    }

    public static IsEqual eq(boolean operand ) {
        return eq(new Boolean(operand));
    }

    public static IsEqual eq(byte operand ) {
        return eq(new Byte(operand));
    }

    public static IsEqual eq(short operand ) {
        return eq(new Short(operand));
    }

    public static IsEqual eq(char operand ) {
        return eq(new Character(operand));
    }

    public static IsEqual eq(int operand ) {
        return eq(new Integer(operand));
    }

    public static IsEqual eq(long operand ) {
        return eq(new Long(operand));
    }

    public static IsEqual eq(float operand ) {
        return eq(new Float(operand));
    }

    public static IsEqual eq(double operand ) {
        return eq(new Double(operand));
    }

    public static IsCloseTo eq( double operand, double error ) {
        return new IsCloseTo(operand, error);
    }

    public static IsSame same( Object operand ) {
        return new IsSame(operand);
    }

    public static IsInstanceOf isA( Class operandClass ) {
        return new IsInstanceOf(operandClass);
    }

    public static StringContains stringContains(String substring) {
        return new StringContains(substring);
    }

    public static StringContains contains(String substring) {
        return stringContains(substring);
    }
    
    public static StringStartsWith startsWith(String substring ) {
        return new StringStartsWith(substring);
    }
    
    public static StringEndsWith endsWith(String substring ) {
        return new StringEndsWith(substring);
    }
    
    public static IsNot not(Constraint c ) {
        return new IsNot(c);
    }

    public static And and(Constraint left, Constraint right ) {
        return new And(left, right);
    }

    public static Or or(Constraint left, Constraint right ) {
        return new Or(left, right);
    }

    /// HINT: not sure about these following 3
    public static Object newDummy( Class dummyType ) {
        return Dummy.newDummy(dummyType);
    }

    /// HINT: what is this?
    public static Object newDummy( Class dummyType, String name ) {
        return Dummy.newDummy(dummyType, name);
    }

    /// HINT: what is this?
    public static Object newDummy( String name ) {
        return Dummy.newDummy(name);
    }
    
    public static void assertThat(Object actual, Constraint constraint) {
        if (!constraint.eval(actual)) {
            StringBuffer message = new StringBuffer("\nExpected: ");
            constraint.describeTo(message);
            message.append("\n    got : ").append(actual).append('\n');
            throw new AssertionError(message);
        }
    }

    public static void assertThat(boolean actual, Constraint constraint) {
        assertThat(new Boolean(actual), constraint);
    }

    public static void assertThat(byte actual, Constraint constraint) {
        assertThat(new Byte(actual), constraint);
    }

    public static void assertThat(short actual, Constraint constraint) {
        assertThat(new Short(actual), constraint);
    }

    public static void assertThat(char actual, Constraint constraint) {
        assertThat(new Character(actual), constraint);
    }

    public static void assertThat(int actual, Constraint constraint) {
        assertThat(new Integer(actual), constraint);
    }

    public static void assertThat(long actual, Constraint constraint) {
        assertThat(new Long(actual), constraint);
    }

    public static void assertThat(float actual, Constraint constraint) {
        assertThat(new Float(actual), constraint);
    }

    public static void assertThat(double actual, Constraint constraint) {
        assertThat(new Double(actual), constraint);
    }
    
    public static HasPropertyWithValue hasProperty(String propertyName, Constraint expectation) {
        return new HasPropertyWithValue(propertyName, expectation);
    }
    
    public static HasProperty hasProperty(String propertyName) {
       return new HasProperty(propertyName);
    }
    
    public static HasToString toString(Constraint toStringConstraint) {
        return new HasToString(toStringConstraint);
    }
    
    public static IsCompatibleType compatibleType(Class baseType) {
        return new IsCompatibleType(baseType);
    }
    
    public static IsIn isIn(Collection collection) {
        return new IsIn(collection);
    }
    
    public static IsIn isIn(Object[] array) {
        return new IsIn(array);
    }
    
    public static IsCollectionContaining collectionContaining(Constraint elementConstraint) {
        return new IsCollectionContaining(elementConstraint);
    }
    
    public static IsCollectionContaining collectionContaining(Object element) {
        return collectionContaining(eq(element));
    }
    
    public static IsArrayContaining arrayContaining(Constraint elementConstraint) {
        return new IsArrayContaining(elementConstraint);
    }

    public static IsArrayContaining arrayContaining(Object element) {
        return arrayContaining(eq(element));
    }

    public static IsArrayContaining arrayContaining(boolean element) {
        return arrayContaining(new Boolean(element));
    }

    public static IsArrayContaining arrayContaining(byte element) {
        return arrayContaining(new Byte(element));
    }

    public static IsArrayContaining arrayContaining(short element) {
        return arrayContaining(new Short(element));
    }

    public static IsArrayContaining arrayContaining(char element) {
        return arrayContaining(new Character(element));
    }

    public static IsArrayContaining arrayContaining(int element) {
        return arrayContaining(new Integer(element));
    }

    public static IsArrayContaining arrayContaining(long element) {
        return arrayContaining(new Long(element));
    }

    public static IsArrayContaining arrayContaining(float element) {
        return arrayContaining(new Float(element));
    }

    public static IsArrayContaining arrayContaining(double element) {
        return arrayContaining(new Double(element));
    }
    
    public static IsMapContaining mapContaining(Constraint keyConstraint, Constraint valueConstraint) {
        return new IsMapContaining(keyConstraint, valueConstraint);
    }
    
    public static IsMapContaining mapContaining(Object key, Object value) {
        return mapContaining(eq(key), eq(value));
    }

    public static IsMapContaining mapWithKey(Object key) {
        return mapWithKey(eq(key));
    }

    public static IsMapContaining mapWithKey(Constraint keyConstraint) {
        return new IsMapContaining(keyConstraint, ANYTHING);
    }

    public static IsMapContaining mapWithValue(Object value) {
        return mapWithValue(eq(value));
    }

    public static IsMapContaining mapWithValue(Constraint valueConstraint) {
        return new IsMapContaining(ANYTHING, valueConstraint);
    }

    /**
     * Verify the expected behavior for the mock registered by the current thread.
     */
    public static void verify() {
        List<Verifiable> mocks = s_mockObjects.get(Thread.currentThread());
        if(null != mocks) {
            for(Verifiable verifiable : mocks) {
                verifiable.verify();
            }
        }
    }
    
    /**
     * Verify the expected behavior for the mocks defined as fields of the arguement object.
     * 
     * @param object the object to be inspected
     */
    public static void verifyObject(Object object) {
        Verifier.verifyObject(object);
    }

    /**
     * Helper method that delegates to {@link #verify()} and {@link verifyObject(Object)}.
     */
    public static void verifyAll(Object object) {
        verify();
        verifyObject(object);
    }
    
    /**
     * Verify the expected behavior for the mocks registered by the current thread and
     * also releases them.
     */
    public static synchronized void verifyAndRelease() {
        Thread currentThread= Thread.currentThread();
        List<Verifiable> mocks = s_mockObjects.get(currentThread);
        if(null != mocks) {
            for(Verifiable verifiable : mocks) {
                verifiable.verify();
            }
        }
        mocks.clear();
        s_mockObjects.put(currentThread, null);
    }
    
    /**
     * Helper method delegating to {@link #verifyAndRelease()} and {@link #verifyObject(Object)}.
     */
    public static void verifyAllAndRelese(Object object) {
        verifyAndRelease();
        verifyObject(object);
    }
    
    ///
    private static synchronized void registerToVerify(Verifiable verifiable) {
        List<Verifiable> mocks = s_mockObjects.get(Thread.currentThread());
        if(null == mocks) {
            mocks = new ArrayList<Verifiable>();
            s_mockObjects.put(Thread.currentThread(), mocks);
        }
        
        mocks.add(verifiable);
    }

    private static DynamicMock newCoreMock(Class mockedType, String roleName ) {
        return new CoreMock(mockedType, roleName);
    }

    private static DynamicMock newClassCoreMock(Class mockedClass, 
                                                String roleName,
                                                Class[] constructorArgumentTypes, 
                                                Object[] constructorArguments) {
        return new CGLIBCoreMock(mockedClass, roleName, constructorArgumentTypes, constructorArguments);
    }

    /**
     * Calculates a default role name for a mocked type.
     * @param mockedType
     * @return
     */
    private static String defaultMockNameForType(Class mockedType) {
        return "mock" + Formatting.classShortName(mockedType);
    }
}

It works for mocking both interfaces and classes (through CGLIB).
And here is a short example of usage (JDK5, because I use static imports):

public class TypeAccessFilterTest {
    @Test
    public void jmockBotNormalRequest() throws IOException, ServletException {
        // static imports
        Mock mockBotChecker = mock(BotChecker.class, new Class[0], new Object[0]);
        Mock mockFilterChain= mock(FilterChain.class);
        TypeAccessFilter taf= new TypeAccessFilter();
        taf.setBotChecker((BotChecker) mockBotChecker.proxy());
        
        mockFilterChain.expects(once()).method("doFilter")
                       .with(isA(HttpServletRequest.class),
                             isA(JSessionidBeautifierHttpResponseWrapper.class));
        
        taf.doFilter(m_mockRequest, m_mockResponse, (FilterChain) mockFilterChain.proxy());
        
        verifyAndRelease();
    }

As far as I know the latest versions of EasyMock allow the same JUnit-free usage, which in my opinion is a great thing.

9 Comments

Filed under Uncategorized

TestNG 5.0 – new annotations and more

TestNG 5.0 - new annotations and more
The new version of TestNG was released. Cedric made the first announcement and the news spreaded quite fast.
The main addition in the new version are the completely revamped annotations. The old @Configuration was replaced by more clear and much more readable annotations: @Before/AfterSuite, @Before/AfterTest, @Before/AfterGroup, @Before/AfterClass, @Before/AfterMethod (phewww… quite a few). But check the following code to see how much better it is:

The “old” way:

public class MethodCallOrderTest {
  @Configuration(beforeTestClass=true)
  public void beforeClass() {
     // do before any test methods in this class are executed
  }
  
  @Configuration(beforeTestMethod=true)
  public void beforeMethod() {
     // do before each test method
  }
  
  @Test
  public void realTest() {
  }
  
  @Configuration(afterTestMethod=true)
  public void afterMethod() {
     // do after each test method
  }
  
  @Configuration(afterTestClass=true)
  public void afterClass() {
  }

  @Configuration(afterSuite=true)
  public void cleanUp() {
      // do once after all tests
  }

}

new way:

public class MethodCallOrderTest {
  @BeforeClass
  public void beforeClass() {
     // hey it looks like I don't need to put any comment here to explain it, ain't it?
  }

  @BeforeMethod
  public void beforeMethod() {
  }
  
  @Test
  public void realTest() {
  }
  
  @AfterMethod
  public void afterMethod() {
  }
  
  @AfterClass
  public void afterClass() {
  }
  
  @AfterSuite
  public void cleanUp() {
  }
}

There are a lot more improvements in this new version: better reports, filtered stack traces, more configuration options for the Ant task.
Last, but not least: don’t worry about the next versions. We already have in mind a couple of more nice things that will make life easier and a lot more pleasant for test developers.

4 Comments

Filed under Uncategorized

A parallel of equality in 2 worlds (Ruby and Java)

Here is a short presentation of equality methods in Ruby and Java:

Ruby Java
Object#equal? ==
Object#eql? Object.equals
Object#== Object.equals
Object#=== N/A

So, in both Ruby and Java we have an instance reference equality or identity (Object#equal?, respectively the == operator).

Another similarity is for objects used as keys in maps (hashes). If you want to customize their behavior, in both Ruby and Java will have to override Object#eql? and Object#hash, respectively Object.equals() and Object.hashCode(). And that would be it with the similarities.

In Ruby world, Object#eql? and Object?== are named equivalence. I haven’t been able to find out the reasons for having both Object#eql? and Object?== and the only example I have found is the following:

2.eql? 2.0 => false
2 == 2.0 => true

Ruby has another equality method Object#=== and this one is used only in case statements.

Reference:

category: , , ,

5 Comments

Filed under Uncategorized

Code reviews and tools (plugins) that may help

After reading Cedric‘s post on Code reviews I remembered that I have used an Eclipse plugin that helped me doing code reviews: Jupiter (I have even submitted at that time some patches [blink/]). As far as I know the plugin is continuously improved so if you are in need for something like this go and get it a try.
Another nice Eclipse plugin that might help with code reviews is Mylar even if its intention is not exactly this one.

3 Comments

Filed under Uncategorized

Stripes?… sounds cool

Being in an investigate/document/read mood these last days, and trying to figure out a good answer to Tim’s question: What Web Application framework should you use? and Matt’s answer, I’ve given a short read to Stripes documentation.
And I must confess that at first glance I like it. It may sound weird comming from an WebWork/SAF developer, but hey, I am doing my best to be objective. I also have to confess that I haven’t got time to really play with it, and I just passed through the documentation, which by the way is well written and clean.
Talking about the rationale behind it (sounds like RoR success story [smile/]):

The main driver behind Stripes is that web application development in Java is just too much work! […] Others, like WebWork 2 and Spring-MVC are much better, but still require a lot of configuration, and seem to require you to learn a whole new language just to get started.

The framework looks like needing almost no configuration (Zero external configuration per page/action (ActionBeans are auto-discovered, and configured using annotations)), tries to eliminate the need to duplicate domain object over the web layer and makes heavy usage of Java5 annotations (f.e. even for URL binding: UrlBinding).

[…] But that doesn’t mean that it can’t run on a Java 1.4 JVM.

and you can read a 2 page HowTo for using Stripes with 1.4 JVMs. There are many other interesting, and I would say important aspects needed for building a normal web app, but I am not gonna describe it here (because I haven’t gained the knowledge to do it and I may present wrong ideas). Here it is a short list of things that I found interesting:

Quick updated: after reading the documentation on site, I have downloaded Stripes and hope to find the time to play with it a little.

6 Comments

Filed under Uncategorized

Annotation driven programming with Eclipse and …

The last few days I have been working on defining some more fine-grained transaction demarcations with Spring and http://themindstorms.blogspot.com/2005/03/annotation-driven-programming-with.htmlAspectWerkz. Read more…

1 Comment

Filed under Uncategorized

QDox, xjavadoc and the alike… maybe one more

Some time ago I was investigating the possibility to have a light in-memory model of java sources. My research has gone mainly to QDox and xjavadoc, passing also through commons attributes.
Unfortunately, after following the mailing list for a long time, I am unable to say that the support for JDK 1.5 will be available soon (or at least at a specific moment in the future – even if the developers are already taking into account this).
So, I get back a little bit and evaluated the problem some other way:

  • how are they implementing these features?
  • why are they implementing this way?
  • which way should i go for?

Answering these will help me find (hopefully) the good way.

How are they implementing these features?
  • QDox: has its own model that is able to keep information about 5 elements: java types, java classes, java fields, java methods and tags. So in order to support JDK 1.5 features, they will need (in big lines) to improve the java type to support generics and add a model class for annotations. Another interesting point of QDox is that it is using its custom java source lexer/parser written in flex and yacc (i guess). They will need also to enhance this too.
  • xjavadoc: has its own model too. In big lines it supports the same elements as QDox does (which in fact represent their real working target). In the same direction, xjavadoc uses its own parser based on JavaCC. So, I would say that xjavadoc has to do the same enhancements as QDox.
Why are they implementing this way?
While the model used in both cases is very clear and I think that with the enhancement I was talking they will be stable for a long time, I am not very sure why both solutions have chosen to use custom parsers. I know that javadoc tool is memory expensive while working with large object graphs, I guess if it is used to parse only bunches of sources and than solve references in memory it would possibly be a viable solution. Here I would like to have some insights of the guys involved in QDox and xjavadoc
Which way should i go for?
I would say that imo QDox seems more alive than xjavadoc (even if the xdoclet guys are working hard). One solution would be to get involved into QDox dev and make/contribute with the enhancements. (But I don’t know if I have a place there as they are already many and I am not sure they are in need for my help). Another solution would be to reinvent half a wheel and go for a solution based only on javadoc parser. While I see some benefits in doing this (assuring the compatibility with the latest JDK available and independence for any custom parsers, and possible to offer access at the code level, without really parsing it), I think I must find out firstly the answer to the above question.

Update: there was an anonymous poster suggesting the solution with javadoc. I think if I choose this solution I must thank him [blink/].

2 Comments

Filed under Uncategorized

Old… but good

Here is an old link to a nice (good) list of Java – to – Relational solutions. Enjoy.

Leave a comment

Filed under Uncategorized

All those NPEs

This weekend I have passed some time checking the code generated by dtoGen™. I have been trying to remove any possibility that a NPE would occur in the generated tool class. (for those not knowing about dtoGen I would recommend a quick read of the intro). I have had to check against NPEs for any instance forced convertor (something like model.getValue().intValue()). I have had to check against NPEs for collections, arrays, maps manipulation… and at a moment I got angry on these NPEs. Why should I check it and not the compiler? (hmmm wait a minute is this possible? would it be fesable? would it be really good?). I sat down for a moment and thought of this. How easy would life be without NPEs! But no, this is not true. The compiler should create check points for any instance variable access or for any instance method call. The code will grow over and over. This is not the last issue. What would it happen when a possible NPE occur? Just signal you? Ignore that piece of code? Wow… after object oriented programming we would begin the fuzzy programming era. I would go home and say: I wrote down today a program. There are many chances it will run. But also many chances it will go a path I don’t even imagine it can.
So, bye bye swearing NPEs. They are a good evil!

1 Comment

Filed under personalog