12/30/07

JUnit 3.8 JUnit 4.x

Recently I looked through some JUnit 3.8 - JUnit 4 stuffs. Here are two useful readings in the subject: First is at IBM, other is on DevX. JUnit 4.X is basically direct improvement of JUnit 3.X with exploiting new features of JDK5. Current version is 4.4 and it can be downloaded from www.junit.org. What have been changed?
  • It needs (surprisingly) at least Java 5.
  • Package has been changed from junit.framework to org.junit.
  • Using @Test annotations instead of naming conventions. Methods must be public with void return type and they shouldn't have parameters. If we don't comply with these we would expect the following runtime exceptions:
    java.lang.Exception: Method xxx should have no parameters
    java.lang.Exception: Method xxx should be void

  • Using static import: import static org.junit.Assert.assertEquals; We can write instead of Assert.assertEquals(...); a sorter assertEquals(...);. (Of course we can use static import with JUnit 3.8 if we have Java 5.)
  • Extending TestCase isn't necessary anymore, so it becames possible to test protected methods by extending the subject class with the class which has the tests.
  • Instead of method setUp() we use @Before annotation, even more than one. Order of executing these methods is theoretically random.
  • tearDown()'s annotation pair is @After, which we can have also more than one.
  • In super classes we haven't have to invoke explicite setUp()==@Before and tearDown()==@After methods because their invocation is automatic: First @Before-s of the super class are invoked, then ones in descendant classes. Order of invoking @After is reversed. First the descendant classes, then super classes.
  • A @Before and @After is invoked before and after every test method as setUp() and tearDown() does. We have the possibility to concede @BeforeClass and @AfterClass which will be invoked before and after all test methods in the given class. There is no such feature in JUnit 3.X. (It has TestSuite class which ensures similar functionality.)
  • If a class doesn't have any @Test annotation, we will get an error.
  • In JUnit 3.X we could check exceptions by writing an assert into the catch block. In JUnit 4 we can define expected exceptions in annotation: @Test(expected=ArithmeticException.class). If exception isn't thrown or different exception has been thrown the test will fail. If more checks needed about parameters and message of the thrown exceptions we must follow the well-known try-catch practice.
  • If we don't want to run some test methods for some reason it's possible to ignore it by using @Ignore. (@Test needn't have to be removed. @Ignore can follow or precede it.) It can have a String-type parameter with the reason why is the test ignored. Test won't run and the runner will sign the fact that it was ignored. We can say @Ignore for the whole class but it's slightly differs from ignoring each test methods one by one, because @AfterClass and @BeforeClass will run in the latter case.
  • Highly appreciated feature to be able to give timeout for the test cases: @Test(timeout=500) Millisec.
  • There is a new assert which compares object arrays, however many (12) assert method removed because of the autoboxing feature. assertXXX(Object, Object) is used instead of them. More precisely DevX writes this happened but oddly I can use these old asserts in the TestCase class.
  • assert keyword of Java1.4 can also be used, however -ea JVM switch must be given at running the tests, otherwise asserts won't be evaluated. When using native asserts, instead of the JUnit's assertException, the general java.lang.AssertionError will raise in certain cases.
  • In JUnit4 there is no suite() method. We can create an empty class which has the runnable classes in annotation:
    @RunWith(Suite.class)
    @Suite.SuiteClasses({My1Test.class, My2Test.class, My2Test.class})
    public class AllTests {
    }

  • By using @RunWith class annotation we can define own runner for the test cases. For an example, the org.junit.runners.Parameterized, which drives the test by a set of parameters we defined previously. A public static method with @Parameters annotation is needed which returns a Collection and a public constructor is needed which can accept elements of the previous Collection. If the Collection contains integer pairs, constructor must have two integer parameters. The runner walks through on the Collection, calls the constructor and the test methods for every element of the Collection. DevX article has a good example about this on the third page. (Listing 2.)
  • Giving @RunWith(TestClassRunner.class) doesn't make any difference than giving anything because the TestClassRunner is the default runner.
  • JUnit4 doesn't make difference between expected failures and wrongly written test cases. This is a stepback. One testcase can have (passed/error/failure) in JUnit 3.8. In JUnit 4 it can have (passed/failure/(ignored)) only.
  • Test can be runned by java –ea org.junit.runner.JUnitCore. It can run 3.8 tests according to the DevX article. Practically 3.8 must have a small modification:
    public static junit.framework.Test suite() {
    return new JUnit4TestAdapter(MyTestClass.class);

    4.0 tests certainly won't run on 3.8. When having both old and new JUnit on the classpath they may impact. It least I had securityException.
  • I've heard about a so called assertThat method. Theoretically 4.4 have this but I didn't see it in the current javadoc on junit.org.
  • Eclipse 3.3 has JUnit4.4 and JUnit3.8 support.

If you need this in Hungarian, click here.

12/1/07

Logger frameworks

Let's have a look round in the world of logging.
There is a glorious article in the Wikipedia about fundamental concepts of logging.

Two (or rather three) competitors are log4j, java logging API == java.util.logging == JUL == JSR47 and Java Commons Logging == JCL. The latter is not a real logging framework, just an adapter which quests for the available framework in runtime and uses it. It can be helpful when we don't want to wrap some modul to log4j, JUL or anything, however, it has disadvantages regarding efficiency and functionality. See this article about it: Think again before adopting the commons-logging API

Here is an opinion about differences between log4j and JUL. I've read it a long time ago and deeply agree with it with the supplement, that because of the continuous inconveniences I hate Java Logging API.

(The author of the former article, Ceki Gülcü is the founder of log4j. He has a blog where he writes engaging things. For an example, mentions presentation of Linus Torvalds about GIT vs SVN. Well, I also didn't like that style not to say about this.)

Nowadays it seems that he (Ceki Gülcü) walks differents ways from Apache group, because he is working on the possible posteriors of log4j and JCL, namely LogBack and SLF4J. (Wikipedia article doesn't mentions these.) Theoretically, SLF4J will have log4j support. I don't know how much will be SLF4J efficient but I guess they started to implement a new framework because they wanted to make something better.

log4j exists since Java 1.1, JUL was invented in 1.4. By exploring homepage of log4j it turns out soon that there's no version which exploits advantages of Java 5.0. Log4j 2.0 would have been the one which fulfils this task, but there are not too much (any) visible activity in this subject.

However, LogBack and SLF4J are going to be in a useable shape soon. LogBack has version 0.9.X nowadays. On our Hungarian forum there was a flame about logBack and using isDebugEnabled. First important consequence was for me, that people do log in many different styles and it depends on the developed application. Somebody can use toString often, somebody doesn't have this possibility. Secondly, isDebugEnabled condition can't be dropped out in every cases, just when there are no expressions in the parameter list. (For sample, explicit high-cost function calls.) By the way, using varargs instead of String evaluation can be rather beneficial during logging.

Which one would I choose? In conservative software modules, when embedding environment may not be log4j-based I would choose JCL. Otherwise I would use log4j. At newly started projects I would use LogBack or SLF4J, although I would get a line if there are existing appenders which I should use. Regarding log4j, (as it is an old professional in the scene) there are a lot of appenders.

(This was a translation again. See original here in Hungarian.)

11/9/07

Wicket vs JSF

This post is the translation of the writing (Hungarian) from my other blog with the identical title.

In the recent months I had the pleasure to get acquainted with Wicket and JSF which are both servlet-based web technology frameworks with identical position and purpose. A Wicket presentation was also organized by Hungarian Javafórum guys at the summer, but unfortunately, I couldn't attend on it.

JSF is part of the J2EE standard, Wicket is a Sourceforge-project which has joined to the Apache Foundation some months ago. Wicket means the implementation itself, while JSF is just a specification with a reference implementation and some real implementations. I met Tomahawk among real implementations, which is also related to Apache.

Wicket uses HTML markup with wicket tags which are replaced to real HTML components in rendering time on the server-side. (Similar to Dojo with the difference, that Dojo replaces components on the client side.) JSF is taglib-based.

We used Facelets with JSF which helps modularization of pages. We also used standard tag library where we could. Instead of writing a long discourse, I've chosen some criterias and here I compare the two competitors:

HTML element set: What kinds of prefabricated elements are present.
Wicket: In the core API, there are just the most basical form components. There aren't sortable table or tree, however a bunch of cool components can be found here: Wicket extensions
JSF: Reference implementation is rather poor, however, there are some more opportunities in Tomahawk. Theoretically, it's possible to mix more implementations by getting the appropriate components even from commercial implementations. There's much room for improvement in Tomahawk JSF components. I've met tree2 which doesn't support default expanded nodes (when showing the tree for the first time, some nodes couldn't be expanded by default without attaching a workaround logic). Generally, a lot of workaround code was needed for creating really usable components, which was very time-consuming and rankling, considering we should spend that time for polishing the application's business logic.

DHTML support: Is it possible to inject javascript into the page or to components and is it possible to refer components?
Wicket: It's okay, but sometimes it's tricky to inject javascript into the pages.
JSF: Referencing components is problematic with the base implementation because it shares identifiers itself. With using "forceId" in Tomahawk, we can specify identifiers, which is basically enough for javascripting.

Logic extensibility: How much can we affect or modify the framework's workflow logic?
Wicket: It's quite possible even to change the code of the framework itself if needed, however, in most cases it's enough to inject logic by implementing and applying specified interfaces.
JSF: It's not easy to intercept, because the JSF engine is outside of the competency of the application. Additionally, JSF page life-cycle is very strict and not too much applicable for some cases. Validation, model update and page render stages have their own unchangeable places. We usually stuck to the problem for a long time when we use more complex validation logic, not to say about multiple forms on a page.

AJAX: They are coming from the pre-Ajaxian era, so Ajax-support is an added feature in each of them. However, supposedly JSF has Ajax-based implementations. (Maybe commercial ones.) Wicket fans say that embedded Ajax support is absolutely good. Practically, it's possible to make nice dynamic functions without writing any line of javascript. In the comment-conversation of the original post I described that I called an application really cool dynamic and "Ajaxified" if it had the same functionality as the Google Calendar. I don't think a JSF or Wicket application could convey this.

Data-model presentation bridge: Model must be pumped into the HTML elements.
Wicket: It happens in Java which is highly comfortable and makes easy to find errors. Hierarchy of the markup must be followed by the Java behind-code, e.g. if a text input is inside a frame stack, the model must contain these frame elements too. Generally, a lots of anonymous inner class must be used for describing the Wicket data-model. It's relatively easy to build in pieces of validation logic.
JSF: Bindigs between the page and the JavaBean-based model is described in XML. So-created model can be detached from the presentation somewhat easier but it needs more boilerplate XML code and JSF can cause further problems. If we manage to create XML without errors and there are no special demands, assembled parts may work in a surprisingly little while. When we want dynamic play, e.g. validation rules of a field depend on another field's value, we might expect problems.

Bugs:
Wicket: It logs quite detailed error messages and stack traces. It's straightforward to find the roots of the error messages in the java code. It's harder to make errors because a lot of potential error is filtered out by the used modern IDEs. Many errors come from mistyping hierarchy between the java behind-code and the HTML markup. It has to be mentioned again, that Wicket pages are simple HTMLs which can be displayed in a simple browser without any server.
JSF: Generally error messages are indirect or even there aren't error messages but anomalies can be seen on the page. Control is empty or it's falled apart. Searching for the missing comma or the mistyped name in the JSF and the XMLs is a 'great fun'. Using some static analyzer for developing JSF application is highly recommended.

Modularity, reusability: Reusability of HTML page fragments.
Wicket: The embedded "fragment" mechanisum can be used. I'd expect much more, however, Wicket fans are delighted with it.
JSF: Facelet support is an amazing hit, nevertheless, it's not direct part of the JSF spec.

Graphic design:
Wicket: As the markup is plain X(HTML), it can be designed by any HTML tool. Images and CSS can be used.
JSF: It isn't plain HTML, but there are more and more WYSWYG JSF editors to be used. Some of them are integrated into graphical IDE-s. (Netbeans, Eclipse, Idea) With these tools I managed to construct simple pages only. Images and CSS can be used too.

I18n: Certainly each of them supports internationalization.

Flow control on pages: Iterations, controlling components' visibility and other properties
Wicket: Doesn't support because it's a base principle that pages don't contain business logic. (But what's about presentation logic-related flow control?) 'Fragment' and 'iterator' mechanism can be used instead of writing direct flow control into the markup. Particular conditions of the iterations and if-else statements are located in the java code behind the page markup. You can switch some component properties also in the java code.
JSF: Supports flow control at more levels by certain tags of the standard taglibs, JSF tags and facelets. However, these mixed technologies don't always cooperate well, which can tremendously increase suck factor.

Server loading: I feel they are in the same level in this question. wicket needs more memory because it must store information about component hierarchy in user sessions. JSF rebuilds server-side representation of component structure upon every HTTP request, which needs increased amount of processing and theoretically settles for less memory. Be aware of serialization when using Wicket, because misconfigured members can easily pull up some megs into the session. Also take care of inactive clients and their sessions. Each of JSF and wicket can be clustered (as I know).

Documentation:
Wicket: it has good docs according to me. People who used more deeply say that it could be better.
JSF: every kind of writings can be found. Tomahawk has a Wiki wich contains mainly descriptions of problems among some useful posts. J2EE specification also has a JSF section.

Which of them would I use in the next web-project?
JSF, although it's somewhat more cumbersome, has more opportunities because it has more implementations. Before choosing JSF I'm sure I would look after a good one. However, if there would be less dynamic form-styled content I would use Wicket because it stands closer to the plain HTML, it's easier to design it, it's easier to code it. For those who are not familiar with JSP-s and taglibs I also would highly recommend Wicket. If there would be more logic, reused and nested model and form elements I would choose JSF. However, it would be too early to forget other web-frameworks. If I would have to make a really dynamic AJAX web-application I would presumably choose another framework beyond these two ones.

Here is another argumentation on the subject. It also contains a Wicket vs JSF opinion strongly on the Wicket-side.

10/27/07

post[0]

I have been writing a blog about Java programming and software technology since 2005. Originally, main purpose of these postings was to ingrain my own thoughts and experiences for myself, but recently I realized that 5 to 10 readers visit these pages per day. Some of these hits come from static links and the more from Google search result pages. Unfortunately, that blog is in Hungarian which is my mother language, so, as I guess, some people finally don't get what they are looking for.

So, I start another one in English to be able to share thoughts with more people, and not least, to improve my English composition skills. :)