TDD for AspectJ Aspects 30

Posted by Dean Wampler Tue, 02 Oct 2007 16:34:24 GMT

There was a query on the TDD mailing list about how to test drive aspects. Here is an edited version of my reply to that list.

Just as for regular classes, TDD can drive aspects to a better design.

Assume that I’m testing a logging aspect that logs when certain methods are called. Here’s the JUnit 4 test:

package logging;
import static org.junit.Assert.*;
import org.junit.Test;
import app.TestApp;

public class LoggerTest {
    @Test
    public void FakeLoggerShouldBeCalledForAllMethodsOnTestClasses() {
        String message = "hello!";
        new TestApp().doFirst(message);
        assertTrue(FakeLogger.messageReceived().contains(message));
        String message2 = "World!";
        new TestApp().doSecond(message, message2);
        assertTrue(FakeLogger.messageReceived().contains(message));
    }
}

Already, you might guess that FakeLogger will be a test-only version of something, in this case, my logging aspect. Similarly, TestApp is a simple class that I’m using only for testing. You might choose to use one or more production classes, though.

package app;
@Watchable
public class TestApp {
    public void doFirst(String message) {}
    public void doSecond(String message1, String message2) {}
}

and @Watchable is a marker annotation that allows me to define pointcuts in my logger aspect without fragile coupling to concrete names, etc. You could also use an interface.

package app;
public @interface Watchable {}

I made up @Watchable as a way of marking classes where the public methods might be of “interest” to particular observers of some kind. It’s analogous to the EJB 3 annotations that mark classes as “persistable” without implying too many details of what that might mean.

Now, the actual logging is divided into an abstract base aspect and a test-only concrete sub-aspect>

package logging;

import org.aspectj.lang.JoinPoint;
import app.Watchable;

abstract public aspect AbstractLogger {
    // Limit the scope to the packages and types you care about.
    public abstract pointcut scope();

    // Define how messages are actually logged.
    public abstract void logMessage(String message);

    // Notice the coupling is to the @Watchable abstraction.
    pointcut watch(Object object):
        scope() && call(* (@Watchable *).*(..)) && target(object);

    before(Object watchable): watch(watchable) {
        logMessage(makeLogMessage(thisJoinPoint));
    }

    public static String makeLogMessage(JoinPoint joinPoint) {
        StringBuffer buff = new StringBuffer();
        buff.append(joinPoint.toString()).append(", args = ");
        for (Object arg: joinPoint.getArgs())
            buff.append(arg.toString()).append(", ");
        return buff.toString();
    }
}

and

package logging;

public aspect FakeLogger extends AbstractLogger {
    // Only match on calls from the unit tests.
    public pointcut scope(): within(logging.*Test);

    public void logMessage(String message) {
        lastMessage = message; 
    }

    static String lastMessage = null;
    public static String messageReceived() {
        return lastMessage;
    }
}

Pointcuts in aspects are like most other dependencies, best avoided ;) ... or at least minimized and based on abstractions, just like associations and inheritance relationships.

So, my test “pressure” drove the design in terms of where I needed abstraction in the Logger aspect: (i) how a message is actually logged and (ii) what classes get “advised” with logging behavior.

Just as for TDD of regular classes, the design ends up with minimized dependencies and flexibility (abstraction) where it’s most useful.

I can now implement the real, concrete logger, which will also be a sub-aspect of AbstractLogger. It will define the scope() pointcut to be a larger section of the system and it will send the message to the real logging subsystem.

Comments

Leave a response

  1. Avatar
    Dean Wampler 11 minutes later:

    Here’s a good article on the developerWorks site (Thanks to Ron Bodkin for pointing this out on the AspectJ mailing list): http://www.ibm.com/developerworks/java/library/j-aopwork11/index.html?S_TACT=105AGX02&;S_CMP=EDU

  2. Avatar
    JoshG 28 days later:

    Darn it, you let my cat out of the bag. While writing JTestMe, which uses aspects to do it’s heavy lifting, I thought to myself, “Me, you need AspectUnit”.

    Thanks for the head-start!

  3. Avatar
    jingjia over 3 years later:

    MTS Converter can help you to convert mts files easily and quickly, and it is very easy to use. if you are in need, you can download it and experience by yourself.

    Main Features of MTS Converter

    • Convert AVC HD(.MTS) to all standard video formats like AVI, WMV, MPG, MOV, DVD, etc and various audio files like AAC, AC3, MP3, WAV, WMA, etc.
    • Support batch conversion, you can import more input mts files to the file playlist
    • Provide rich profiles, customize and save your profile for future use
    • Capture current pictures by click “snapshot” and save the current image to snapshot folder
    • Supports extract audio, pictures from video
    • Split one source file to several
  4. Avatar
    film over 3 years later:

    I was very pleased to find this site. I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

  5. Avatar
    Designer Bags over 3 years later:

    Awesome article!Thanks for ur nice sharing!!!

  6. Avatar
    iPhone SMS transfer over 3 years later:

    So easy to backup iPhone SMS to computer.

  7. Avatar
    Pandora over 3 years later:

    However RSpec uses an alternative syntax that reads more like a specification than like a test. Let me show you what I mean.

  8. Avatar
    DRM removal software over 3 years later:

    You know, to be a good programmer is not so easy. it is not to understand it, however, you can finish it, enjoy much. want to Know more about this topic.

  9. Avatar
    pandora over 3 years later:

    Had a pleasant respond nearly accomplished, had been evidence reading this & received damaged through an ad pertaining to Shipwreck beads. Been age ranges since I checked out in the following & left because the large web site alterations lsat summer built taking part through dial-up Distressing. I discover the situation is a very similar. Sleepless & popped more than from the Etsy community forums which in turn did not seize me tonight… Spend time hanging out on the community forums & perusing goods available for sale & recently marketed. There have been around 197,500 jewelry listings once i opened up our go shopping (NGHDesigns) in late August. There are over 300,000 today. I’ve acquired a number of good results & take pleasure in taking part right now there, nevertheless are glad it’s not how you preserve any top more than the heads. Some retailers do very well there, other folks in no way offer anything. Even one of the most amazing items are usually laid to rest inside heap in only units.

  10. Avatar
    http://www.blacktowhiteiphone4.com over 3 years later:

    iphone 4 white and iphone 4 black, which one will be more suitable for yourself? Thinking of the black iphone 4 is too ordinary, iphone 4 white will be the one to make you feel different.

  11. Avatar
    Silicone Molding over 3 years later:

    Intertech Machinery Inc. provides the most precise Plastic Injection Mold and Rubber Molds from Taiwan. With applying excellent unscrewing device in molds, Intertech is also very professional for making flip top Cap Molds in the world.

  12. Avatar
    iPad to mac transfer over 3 years later:

    Thanks for shareing! I agree with you. The artical improve me so much! I will come here frequently. iPad to Mac Transfer lets you transfer music, movie, photo, ePub, PDF, Audiobook, Podcast and TV Show from iPad to Mac or iPad to iTunes.

  13. Avatar
    Criminal Records over 3 years later:

    Now, the actual logging is divided into an abstract base aspect and a test-only concrete sub-aspect

  14. Avatar
    dswehfhh over 3 years later:

    We are the professional clothes manufacturer and clothes supplier, so we manufacture kinds of custom clothes manufacturer. welcome you to come to our china clothes manufacturer and clothes factory.

  15. Avatar
    iPad Video Converter for Mac over 3 years later:

    Our backup software can help you take a snapshot for your contacts and SMS. Your important personal information will be never lost.

  16. Avatar
    cheap true religion los angeles over 3 years later:

    hni

    The straight jeans trousers mens jeans on salefolded up look, put the pants into the pant low price true religion jeansfor summer and fall,
  17. Avatar
    Berg over 3 years later:

    there is a a clear difference between being gay and being a rapists or paedophile. For you to compare them is quite frankly laughable.

  18. Avatar
    Cris over 4 years later:

    This is another informative post. I like it. Thanks. – roof venice

  19. Avatar
    okey oyunu oyna over 4 years later:

    ooo very good

    internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.

  20. Avatar
    real estate advertising over 4 years later:

    great job.. wow… the best website.. i love it here.. i gain a lot of information.. thank you for this article.. i love it.

  21. Avatar
    handbags for sale over 4 years later:

    I wasn’t able to donate, but I’m glad you’re doing better now! Also, your boys are adorable!!

  22. Avatar
    christian louboutin shoes on sale over 4 years later:

    These christian louboutin patent leather pumps are just the same as selling in the franchise store.Or even better. Quite cheap christian louboutin leather platform pumps.I could say this is the best one I have ever ordered online.

  23. Avatar
    beats by dr dre headphones over 4 years later:

    The article has been finished.

  24. Avatar
    Hancy over 4 years later:

    Hello Friend,Whichever style of Fashion Shoes you’re looking for, classical, fashionable, lovely or the latest design, you can find your favorite designer shoes in www.dunkpage.com ,several days ago I bought one pair of shoes from there,It’s beautiful and very comfortable!

  25. Avatar
    beats by dre store over 4 years later:

    lovely or the latest design, you can find your favorite designer beats by dre sale cheap beats by dre

  26. Avatar
    cheap juicy couture tracksuits over 4 years later:

    Don’t stop blogging! It’s nice to read a sane commentary for once.

  27. Avatar
    shanewatson404@gmail.com over 4 years later:

    I have really Legal Assistant Job Description admired for the nice info is Director of Operations Job Description visible in this blog that to amazing technology Accounting Job Description is visible in this blog Graphic Designer Job Description This is an interesting articles in this blog that to using the simple language in this blog

  28. Avatar
    Tips For Bowling over 4 years later:

    Law in general is human reason, inasmuch as it governs all the inhabitants of the earth: the political and civil laws of each nation ought to be only the particular cases in which human reason is applied.

  29. Avatar
    christian louboutin over 4 years later:

    Peep toe shoes used to be popular, now it regress popular again. Too heavy and dramatic square toe shoes may be nightmare for many people, but open a mouth in front, the effect will be greatly different. For women, it is a very good transition. It is very trendy, but unlike pointed toe shoe so eye-catching. In this year, a pair of delicate Christian Louboutin Peep Toe Pumps will be a good choice.

    Christian Louboutin Madame Butterfly 150 Suede Pumps Red

    Technical details of Christian Louboutin Madame Butterfly 150 Suede Pump Red:

    Color: Red
    Material: Suede
    Peep toe
    6(150mm) covered heel
    1.5(35mm) covered platform

    Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Peep Toe Pumps, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.

  30. Avatar
    alwadifa 2012 over 4 years later:

    that’s a very good article about java i helped me a lot

Comments