May 19 2009

How to customize your jUnit Behavior and Interaction

Category: Java,Misc,Testing,UbuntuPhil @ 8:17 pm

I have tried to walk through the jUnit source code a couple of times, trying to figure out how to implement my own behavior; only to give up in frustration (no I did not read the documentation, real developers don’t do that, they Google!) Why would I want to implement my own behavior? Well, it always seems to center around integrating with Spring. I usually want/need to do control the way the context is being created or do something immediately before the context is loaded or as the context is loading; something that might not be possible not possible using a @BeforeClass annotation.

This problem was actually related to my previous blog on Implementing Custom Scopes in Spring. Because I implemented some beans using the session scope, I kind of created a catch-22 scenario;  I have tried to capture the problem in bullet form:

  • Each jUnit test needs the ability to specify the specific test user (role, user info, etc.) that is relevant for that individual test
  • The test user profiles are configured and controlled by a Spring managed bean
  • All beans are lazy-init = true and injected into the unit test using the @Resource annotation
  • The session scope beans need to have the SecurityContextHolder configured with the appropriate principal (test user), before they are created
  • So, the problem is: How do you specify the test user, before the session scope beans are created and injected into the unit test class?

In a normal execution environment, using the Spring Security filters and a Servlet, the SecurityContextHolder would have been assigned using the authenticated principal, before creating any Spring dependencies. Because I created my own custom scopes for unit testing, the SecurityContextHolder was null and the session scope beans constructor was failing an assertion (principal != null). I could have easily fixed this by adding a pre-authenticated user to the SecurityContextHolder, using some static method approach,. However, because my mechanism for handling test users was itself a Spring bean, I had no possible way of specifying before the beans were injected into my unit test.

When jUnit 4.0 was released, it added several new constructs that make some very elegant solutions. I don’t think most developer’s ever look beyond the base jUnit functionality; fortunately it seems to solve 99% of the typical test scenarios. The new constructs are actually specified via annotations, they are the @RunWith and @TestExecutionListeners. My example code, can probably be made a little cleaner, but my main goal was to get the unit tests working. Because you don’t directly create any of these objects, you have to be aware of the timing; implement your customizations at  the correct point in the lifecycle. Another interesting problem, is that you don’t actually create the Spring Context, but you can interact with it via listeners.

First, we need a class which extends DependencyInjectionTestExecutionListener. This base class is required when using Spring and provides several override-able methods. I needed to configure the SecurityContextHolder, before any beans were injected into the unit test; I could accomplish this by utilizing the injectDependencies method. To support my testing needs, I added two (2) properties to the sub-class (this could have been cleaner); one to specify a user from a “user provider” factory, and a simpler one that used the user id of the person running the test. As you can see from the code, before an beans are injected into the unit test, I have access to the Spring context. This allows me to request the “user provider” factory and then request a specific test user. At this point, I can now assign the user to the SecurityContextHolder; all before any of the session scope beans are created.

public class AuthorizedTestExecutionListener extends DependencyInjectionTestExecutionListener {

    private TestUserAuthorization defaultAuthorization;
    private String                junitAuthorization;

    public void setJunitAuthorization(final String junitAuthorization) {
       this.junitAuthorization = junitAuthorization;
    }

    public void setDefaultAuthorization(final TestUserAuthorizationdefaultAuthorization) {
       this.defaultAuthorization = defaultAuthorization;
    }

    @Override
    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    protected voidinjectDependencies(final TestContext testContext) throws Exception {
       if (StringUtils.isNotBlank(junitAuthorization)) {
           final Authentication login = new UnitTestAuthenticationToken(this.getClass().getSimpleName());
           SecurityContextHolder.getContext().setAuthentication(login);
       }
       else if (defaultAuthorization != null) {
           finalTestUserModuleManager manager = (TestUserModuleManager) testContext.getApplicationContext()
                    .getBean(defaultAuthorization.testUserManager());
           final SecureUserInterface user = manager.find(defaultAuthorization.principal());
           final Authentication login = new UnitTestAuthenticationToken(user);
            SecurityContextHolder.getContext().setAuthentication(login);
        }

       super.injectDependencies(testContext);
    }
}

Next, we need to extend SpringJUnit4ClassRunner. This class is responsible for for creating the Spring test context and  DI listener class.  By over-ridding the  createTestContextManager, you have the opportunity to configure the test execution listeners.  I  also created two custom annotations, TestUserAuthentication and  JUnitAuthentication.  Using either one of these annotations, I could provide run-time meta-data  to my  custom AuthorizedSpringjUnit4ClassRunner; the meta data was then used to configure my custom  AuthorizedTestExecutionListner.

public class AuthorizedSpringjUnit4ClassRunner extends SpringJUnit4ClassRunner {

    public AuthorizedSpringjUnit4ClassRunner(final Class<?> clazz) throws InitializationError {
       super(clazz);
    }

    @Override
    @SuppressWarnings("PMD.ConfusingTernary")

    protected TestContextManager createTestContextManager(final Class<?> clazz) {

       final TestUserAuthorization defaultUser = clazz.getAnnotation(TestUserAuthorization.class);
       final JUnitAuthorization jUnitUser = clazz.getAnnotation(JUnitAuthorization.class);

       final TestContextManager context = super.createTestContextManager(clazz);

       for (final TestExecutionListener l : context.getTestExecutionListeners()) {
           if(AuthorizedTestExecutionListener.class.isAssignableFrom(l.getClass())) {
               if (defaultUser !=null) {
                    ((AuthorizedTestExecutionListener) l).setDefaultAuthorization(defaultUser);
                }
               else if (jUnitUser != null) {
                    ((AuthorizedTestExecutionListener) l).setJunitAuthorization(clazz.getSimpleName());
                }
            }
        }
       return context;
    }
}

Once you understand what all of the pieces do, they are super easy to customize to provide enhanced behavior. I think my solution provided a very clean, elegant solution for providing test specific user profiles, on a test by test basis.

@RunWith(AuthorizedSpringjUnit4ClassRunner.class)
@TestExecutionListeners(AuthorizedTestExecutionListener.class)
@ContextConfiguration(locations = {//
"/com/beilers/resources/spring/contexts/jUnitContext.xml" //
})

public class UnitTestHelper {
...
}
https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


May 17 2009

Unit Testing Custom Spring Scopes

Category: Java,TestingPhil @ 6:45 pm

I recently worked on a JSF-based application that was integrated with Spring, both the Core Framework as well as the Spring Security Framework. I certainly don’t have it all mastered, but the experience has given me multiple topics to blog about! We decided to let Spring manage all of the beans, rather than making JSF manage some of the beans and Spring manager the rest. I liked the consistency and thought it would make unit testing easier. Spring provides two basic scopes, singleton and prototype. When you add Spring Security into the mix, you get two additional scopes, one for session and another for request.

This should have been no big deal. To my surprise, when I wrote my first unit test, I discovered the session and request scopes were not supported; the bean factory threw an unsupported scope exception when I asked for the bean. Googling did not lead to any exact answer, but I found lots of examples; many developers seem to implement a thread scope. I simplified one of the many implementations I found, as I only need to support unit testing.

The first step is to build your own class that implements the Spring Scope interface. I created a generic class, such that I could use it for any custom scope.

public class CustomScopeHandler implements Scope {

     private final Map<String, Object> hBeans = new HashMap<String, Object>();

     public Object get(final String name, final ObjectFactory factory) {
        Object result = null;

        if (hBeans.containsKey(name)) {
            result = hBeans.get(name);
        }
        else {
            result = factory.getObject();
            hBeans.put(name, result);
        }

        return result;
    }

    public Object remove(final String name) {
        Object result = null;

        if (hBeans.containsKey(name)) {
            result = hBeans.get(name);
            hBeans.remove(name);
        }

        return result;
    }

    public String getConversationId() {
        Assert.state(true, “Needs to be implmented – ConversationId”);
        return “N/A”;
    }

    @SuppressWarnings(“PMD.DoNotUseThreads”)
   public void registerDestructionCallback(final String name, final Runnable callback) {
        Assert.state(true, “Needs to be implmented – DestructionCallback”);
    }
}

The next step is to add your custom scopes to the IoC container. Using the Spring CustomScoptConfigurer class, you can easily add as many scopes as you like. Pretty simple! Now you can execute your unit tests as you would have initially expected. One thing to be aware of, this implementation treats beans as if they are singletons. You could easily eliminate the Map and return back new instances on each invocation. It all depends on your specific needs, mine were pretty simple.

      <bean class=”org.springframework.beans.factory.config.CustomScopeConfigurer”>
            <property name=”scopes”>
                  <map>
                        <entry key=”request”>
                              <bean class=”test.scope.CustomScopeHandler” />
                        </entry>
                        <entry key=”session”>
                              <bean class=”test.scope.CustomScopeHandler” />
                        </entry>
                  </map>
            </property>
      </bean> 

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Apr 23 2009

Moving from Continuous Integration to Continuous Testing…

Category: Java,TestingPhil @ 1:01 am

I have been following Kent Beck on Twitter for some time, keeping an eye on his jUnit Max product. I think it is a very cool idea, especially with the Eclipse integration. If you have a well written jUnit suite, this could be pretty slick. I only wish Kent would kill the subscription idea; I can’t really blame him for wanting to make money, he just won’t be getting any from me! It is a bummer the tool is not free. It is hard enough to get some developers to build unit tests, now I’m going to charge them a subscription fee to execute the tests… Not happening!

Here was a short little post on the concept. Give it a read and share your thoughts…

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Apr 22 2009

Validating and Managing Argument Dependencies with Args4J

Category: Java,TestingPhil @ 7:17 pm

I recently reviewed some Java code that was designed to process a set of arguments; my first thought… there has to be a better way! I did a quick Google search and found multiple command line processor implementations. My favorite seems to be the Args4J implementation. I like the simple Java Bean approach, taking advantage of Java 1.5 annotations, enumerations, and generics. The best part is the auto-magic type conversion from string arguments to bean properties. It feels a little like Apache BeanUtils, but the annotation processing makes it more flexible.  A pretty slick implementation, but with a couple of small tweaks, would have been even better.

The Args4J implementation provides an ample collection of option handlers to support automatic type conversion of the basic Java types. Option handlers are provided for the all of the numeric types, URLs, Files, bounded lists (enumerated values), as well as unbounded lists. The implementation is easily extended; custom option handlers can be added to support your own object types or specific input formats, such as dates.

Overall, Args4J is very well done; I would have liked to see a little more support in the following areas:

  1. Args4J provides no default support for handling Java Date Types. I created a simple abstract option handler to support any data format.  A concrete class is required for each desired format; but the subclass only needs to provide the requested date string format. An abstract date handler class might be a nice addition to Args4J, even though it was very simple.
  2. Args4J does not provide any type of argument validation, beyond basic type conversion. In my AbstractDateHandler class, I implemented a validate(<T> value) method. The validate method is invoked before the date instance  is “set” on the bean.  This implementation allowed me to ensure the specified date was before today’s date.  This was really pretty clean; if the specified date was in the future, the option handler threw a CmdLineException containing the validation error in the message. This exception was handled up the call stack, just like any other type conversion issue, no special coding required.
    • I can see this being very useful for numeric types as well. Maybe only positive integers are valid for as a specific parameter. The current Args4J implementation provides no way to seamlessly provide this type of validation via the Option Handlers (without cloning an the existing handler).
    • This type of validation can be implemented in the Java bean, but the annotation must be specified on the setter, rather than the property.  Some developers might actually prefer the validation logic it in the bean. Personally, I would rather see this logic managed by the option handler.
  3. The biggest hole in the implementation is the management of argument dependencies. For example, it would be nice to validate if the specified start date parameter is before the end date parameter, or if the print parameter is specified, the filename parameter is not allowed. This type of validation can be implemented in the bean, but would be invoked outside of the argument processing flow. You will have to mange exception logic in two places, once for the “type conversions” and another for the intra-argument dependencies.
    • There are some flaws in my theory, but I thought it would be better if the option handlers had some knowledge of their own dependencies. My theory works well for required options, but not so well for optional ones.
    • I created a custom CmdLineProcess class, which was hidden by suggestion #4 below. This class owned a dependency manager instance which made the previously processed command line values available to the current option handler.
    • An ArgumentsDependency class was accessible during the validation process. The handler could now ask the dependency manager for values that were processed by other handlers. In this example, the EndDateHandler is asking for the dependency manager for the value parsed by the StartDateHandler.
    • I know this is not perfect, but I really like the way the validation is implemented in a consistent manner, making it possible to handle all exceptions the exact same way.
  4. The implementation also provides a Starter class, which eliminates the need for the developer to write a main() method. It is an interesting idea, but I need to give this style a little more thought! I like having my options class independent of the execution class. The Starter approach merges the options and driver (main) logic into one single class.  I would have preferred to see an argument processor class, with a method like: public T parseArgs(final String[] args, final Class<T> clazz). The argument processor would catch all of the exceptions and output the validation errors and usage information; the caller would need to do no extra processing or validation.

I hope this gives a little more insight into how Args4J is actually implemented and one possible method for extending it. Maybe someone has already handled these problems in a more elegant manner, but I did not to change any of the Args4J source code. That restriction did not give me a lot of flexibility to implement my enhancements!  Overall, Args4J is a simple and elegant solution for sometimes messy problem.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Mar 03 2009

Evolution: Emacs to Eclipse

Category: Eclipse,JavaPhil @ 11:10 pm

Early in my software development career, I had the good fortune to be mentored by someone who was an Emacs guy.   After much complaining about the crazy, obscure key combinations, Emacs became my weapon of choice and I actually became pretty good at hacking LISP! I am still an Emacs guy, but only those crazy key bindings live with me today. We used to joke that Emacs was not an editor, but an operating system! I would start up Emacs in the morning; it was the only tool I needed all day. I could read my email, read news, compile code, debug, and even play games (which I never did, but thought it was cool!).

So, why is this history lesson important? It is all about focus and productivity. By allowing the developer to accomplish multiple activities within a single tool, helps them stay focused on the task which they are trying to complete. By minimizing the need to switch tools, the developer can easily toggle between the different activities, without interruption. Think about all of the different tasks that one does developing software; the most basic ones being managing problem tickets or programming assignments, interacting with the configuration management system,  writing code, and executing unit tests.  I have worked in environments where every tool operated in its own isolated world, with little or no integration to other tools. Each time I changed tasks, it was like a huge context switch: 1.) start the problem ticket tool 2.) Locate the ticket information 3.) Put the ticket in the correct state 4.) Check out the code 5.)  Edit the code 6.) Test the code  7.) Repeat selective steps.  Quite a process; it could actually involve using four different tools, just to change the code! The problem is even worse, when you are working on multiple tickets?  It can be a little more than challenging to keep the changes associated with the proper ticket.

Eclipse and other Integrated Development Environments (IDE) have evolved into the world that was once dominated by Emacs. These IDEs have literally hundreds of custom plug-ins that allow the developer to stay focused on the task at hand.  The IDE provides more than simple access to the supporting tool (via a plug-in), well designed plug-ins are able to integrate information into the current context of the developer’s activity. Plug-ins seem to take one of two integration approaches, task management or task support.  I consider task management a major activity such as ticket management or debugging. The plug-in developer would provide a big picture (multi panel) view of that task, a perspective in Eclipse terminology. From this perspective, the developer can focus on all of the activities that are relevant to that task. Task support is the alternate integration approach; this allows the developer to customize the task management perspective, by adding additional, supporting  panels; a view is Eclipse terminology. These panels show specific, subset information about different, potentially related task, such as coding problems, J2EE server status, or a selected class hierarchy.

It is this customization and integration with the task management perspective that highlights the true power of an IDE. Simple integrations include code quality plug-ins that highlight non-conforming or poorly structured code as the developer is type. One of my favorites is integrated code coverage tools; untested conditionals and statements are automatically highlighted in the editor after running a unit test.  This is the big win, focus plus productivity. Developers can now concentrate on their primary task and the output from supporting tools is seamlessly weaved into the process by the IDE. No need to switch windows or applications, everything they need is right there in front of them, exactly when they need it.

Just like many of my posts, they started off in one direction and end up in a completely different one! I really wanted to write about an interesting plug-in called Mylyn, which is a task focused interface for Eclipse.  The integration aspect of Mylyn with Eclipse is very  intriguing. Hopefully, my next post will explore how Mylyn could be used to make developers more focused and provide management with a more realistic perspective of the project’s progress.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Feb 09 2009

Spring Utility Classes…

Category: JavaPhil @ 9:41 pm

Call me lazy or crazy, but I have never really taken the time to look at everything that the Spring Framework can provide. I read an interesting web page the other day, complaining about the size of different Java frameworks. The author ranked Spring as the number one in “Complexity Pain” with over 2,400 classes. If you think about it, that is really amazing . Out of curiosity, I decided to look at the JavaDoc index for the Core Spring framework. It is actually quite impressive or quite paralyzingly!

Sometime back, I discovered something in Spring that I doubt is all that well known, but probably very useful to the average Java project, the Spring Util package.  I once worked with a developer who liked to put guard statements inside all of his methods. He created his own assertion class that would look for null values or null parameters, and create informative exceptions when the method was used incorrectly (the guard was true). It was a little more helpful than the basic null pointer exception and much more convenient than adding a bunch of “if” blocks. While I was not accustomed to this programming style, I ultimately became more accepting of this practice. One day when I was creating a jUnit test, I accidentally discovered the Spring Util Assert class. The Spring Assert class had many more guard options than the one we used and the additional benefit of not being in our code base! Code is a liability… as one of my friends likes to say!

I would highly recommend that anyone using Spring become familiar with the classes in the Util package. I was actually quite surprised by the variety of support; from Java 5 annotations, collection utilities,  numeric conversions, to the copying of files and many more.  If you really think about it, the large number of support classes should not be all that surprising. Developers always seem to need these type of classes when building non-trivial software. Obviously, the more interesting and valuable Spring classes (the reason you would actually want to use the Spring Framework!) required these reusable utility classes to provide the overall functionality. So, why don’t we take advantage of them too?

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Nov 23 2008

Unit Testing with Spring 2.5.x

Category: Java,TestingPhil @ 1:08 pm

Sometime back, using the Spring Framework and jUnit 4.x was not very elegant. Spring only supported dependency injection by sub-classing their AbstractDependencyInjectionSpringContextTests class. The coolest thing about jUnit 4.x was the implementation of annotations and the elimination of the requirement to extend the jUnit TestCase class. Obviously, this was considered an issue by many people, as several projects created their own solutions for jUnit 4.x integration. One such implemenation was Unitils, which I used on several projects. I did not take advantage of all of the Unitils features (Mock Objects, JPA, or DBUnit integration), only the dependency injection and a little of the Hibernate and Transaction management support.

Someone recently hipped me to the fact, that somewhere along the way, Spring finally added support for jUnit 4.x. I wanted to see if I could possibly eliminate the need to Unitils.  Only have only played with the integration for short time, but it appears to do what is required. The only real issue I encountered was having to downgrade from jUnit 4.5 to jUnit 4.4.  Unfortunately jUnit 4.5 broke the integration, and will not work. However, moving back to jUnit 4.4 solved all of the issues.

The basic class level annotations that you need to be aware of are @RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = { “/com/sample/resources/applicationContext.xml” }).  I have seen the @RunWith annotation used by many new jUnit extensions, it seems pretty cool. The ContextConfiguration is pretty obvious, you can provide a list of XML files which contain your Spring context

Next you can simple provide the @Autowired or @Resource annotation to your test class properties. Spring will then inject those objects for you at execution time. They did provide the @Qualifier(“alternateBeanName”) annotation which allows you to remove possible ambiguity.

One thing that was not entirely obvious to me was the @TestExecutionListeners annotation. One of the Spring examples had it set to {}, which effectively turns off the dependency injection. It would have best to leave it out! Anyway, there are several other Listeners that you might want to be aware of, such as dealing with Transactions and a dirty spring context.

On of the more interesting annotations, (which was not in Unitils) was the idea of making tests specific to an environment. While this  is probably not that common, I have had situations where I can only run a test in the CI (Continuous Integration) environment, or maybe only I only want it to run on my development box. The @IfProfileValue annotaion provides this ability. The default implementation allows you to do simple “if logic” base on Java properties. It is also possible to define your own configuration (something that determines the value of the requested attributes) class, using the @ProfileValueSourceConfiguration(Include.class). Pretty cool, I can actually see using this feature in the future.

There are plenty of other annotations that will be useful, such as @BeforeTransaction, @AfterTransaction, @Rollback, and @NotTransactional.

I believe that the @RunWith and @ProfileValueSourceConfiguration annotations can be very useful in building a consistency unit test strategy, effectively hiding much of the noise associated with most jUnits (noise = configuration and setup tasks). Personally, I find jUnit 4.x much more elegant that the original (pre 4.x) strategy, providing a much cleaner implementation.

I believe that unit testing is essential to projects, and will continue on my personal mission to push for Test Driven Development. I truly believe that done right, “Testing is basically Free”… especially when you consider the integration environments provided by Spring and development tools such as Eclipse. How can anyone afford NOT to test?  Enough soapbox for the day, here was yet another little TDD article.

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Oct 03 2008

What's up with creating your own loggers?

Category: JavaPhil @ 6:18 pm

I have been pushing SLF4J for a long time now… When talking with other developers, (even when I talk to myself!) they have such strong convictions to “how they implemented it last time”, that it is really hard to get them to consider something different. Especially when it is as boring as logging!

I can’t tell you how many App1Logger.java, App2Logger.java, logger framework implementations I have seen over the years. When JDK 1.4 logging was introduced, (good or bad), I jumped on it. It was nice to not have to “have discussions” about what logging API we were going to use. I personally hated all of the wrappers (this dislike goes beyond logging wrappers too!)

So where is this going? I had an interesting idea yesterday when talking to someone about SLF4J. I believe that SLF4J is more of an API than an implementation. SFL4J provides a logging API and a collection of plug-able implementations. One could say that JCL (Jakarta Commons Logging) is an API, but also includes a “magic” implementation picker. This implementation picker is wired into JCL, defining a specific implementation philosophy. This philosophy has proven to be way more pain than gain. As for as the JDK1.4 and Log4J frameworks, I would classify them as purely implementations, with a matching, uncouple-able API.

Then it hit me… I can roll my own implementation and plug it in under SLF4J. I really don’t what to roll my own, but the point is that I can add custom behavior to my logging system without creating a wrapper framework. I think this is pretty cool!

So, that really only leaves one question: do you like the SLF4J logging API? Sure, it has some short coming, but what code does not? Overall, I think it is a perfectly sufficient API for the needs of anything I’ve encountered.

Once again.. call me crazy!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Sep 28 2008

Unit Testing is Dumb….

Category: JavaPhil @ 6:53 am

I was surfing for something last night and happened to run across this blog on unit testing.  Apparently, encouraging unit testing has turned into one of my personal missions. I don’t think testing is second nature to most developers. For me, the very first thing I do when starting a project is making sure that jUnit works. I also try very hard to write the test first, followed by the code… this is a much harder habit to develop!

There were two points that seemed to resonate with me that I seem to experience every day…

  • The difference between thinking code works and knowing it works with
    a mountain of evidence to back you up.
  • Reproducing a customer problem in minutes by extending an existing
    test and fixing the problem.

Important or not? They work for me!  Anyway, the two related post were entitled “Easy 2 Test == Less Reason to Test” and “Unit Testing is dumb

I really recommend reading the first one, as it makes some very good “Random Observations”.  Additionally, I really like this guy’s site, the graphics are really unique. (He must have an Apple!)

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


Sep 08 2008

Restful Web Services…

Category: JavaPhil @ 8:04 pm

I was actually looking for information to help me setup an Ivy2 repository and ran into this information on the IBM site…. I honestly did not read it all yet… but it looked interesting! A two part web blog.

Project Zero (Part1, Part2)

If you happen to be interested in Ivy, this might be a good read too!

https://www.beilers.com/wp-content/plugins/sociofluid/images/digg_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/reddit_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/dzone_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/delicious_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blinklist_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/blogmarks_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/google_48.png https://www.beilers.com/wp-content/plugins/sociofluid/images/facebook_48.png


« Previous PageNext Page »