• Home
  • RSS Feed
  • Log in

Latching and mocking in concurrent tests
Posted by Iwein Fuld mid-afternoon: November 3rd, 2009

Concurrent testing is hard, but not as hard as you think. If you use the right tricks it can be done. This blog shows you one particular trick that uses a latch and a mock to ensure a test scenario is completed before running the verifications.

While working on Spring Integration in Action, I experimented with a neat solution for concurrent tests. When I showed it to some colleagues I was pleasantly surprised by the reaction that I got. Judge for yourself if it's worth the blog.

The main idea is to use a latch and let your mock count it down. It sounds trivial (and to be honest it is).

First let me show you how it would be done without mocking:

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ConcurrentTest {

  @Autowired @Qualifier("in") MessageChannel in;

  @Autowired @Qualifier("out") PollableChannel out;

  @Autowired Service service;

  @Test(timeout = 5000)
  public void shouldGoThroughPipeline() throws Exception {
    in.send(MessageBuilder.withPayload("test").build());

    service.invoked.await();
    out.receive();
  }

  public static class Service {
    private CountDownLatch invoked = new CountDownLatch(1);

    public String serve(String input) {
      invoked.countDown();
      return input;
    }
  }
}

A message is sent on channel "in", which will result in an asynchronous invocation of the service. I'm using Spring Integration to make the test asynchronous, but I could just as easily have used @Async, Camel, JMS or what not. The basic idea remains the same.

This is already mostly painless, but we clean up the test a bit more by using a mock. You can wire a mock into your context using a factory-method:

<bean id="service"  class="org.mockito.Mockito" factory-method="mock">
  <constructor-arg value="iwein.samples.test.concurrent.ConcurrentTest$Service"/>
</bean>

Now this mocked service will be autowired into the test and you can make it do tricks:

  @Test(timeout = 5000)
  public void shouldGoThroughPipeline() throws Exception {
    final CountDownLatch serviceInvoked = new CountDownLatch(1);
    given(service.serve("test")).willAnswer(new Answer(){
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        serviceInvoked.countDown();
        return "test";
      }
    });

    in.send(MessageBuilder.withPayload("test").build());

    serviceInvoked.await();
    out.receive();
  }

The answer passed into willAnswer() method will first count down the latch and then return "test". This works, but it's not the most readable code. Let's tidy it up a bit:

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ConcurrentTest {

  @Autowired @Qualifier("in") MessageChannel in;

  @Autowired @Qualifier("out") PollableChannel out;

  @Autowired Service service;

  @Test(timeout = 5000)
  public void shouldGoThroughPipeline() throws Exception {
    //given
    final CountDownLatch serviceInvoked = new CountDownLatch(1);
    given(service.serve("test")).willAnswer(latchedAnswer("test", serviceInvoked));

    //when
    in.send(MessageBuilder.withPayload("test").build());
    serviceInvoked.await();

    //verify
    Message<?> message = out.receive();
    assertThat((String) message.getPayload(), is("test"));
  }

  private <T> Answer<T> latchedAnswer(final T returning, final CountDownLatch latch) {
    return new Answer(){
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        latch.countDown();
        return returning;
      }
    };
  }

  //You'd have a class in main to mock, but an interface here will serve the example
  public static interface Service {
    public String serve(String input);
  }
}

That's really polite code for a concurrent test don't you think?

I'm thinking of adding the latchedAnswer method into a test utility that comes with Spring Integration, but as you can see it fits quite well in your copy buffer too. The point is that even without using a concurrent test framework (I know they're out there) simple concurrent tests can be as simple as they should be.

Caveats:

  • If you pass an instance of the wrong type into latchedAnswer you'll not get a compiler warning, because of a generics issue with Mockito
  • When you replace a service with a mock, frameworks using reflection around it might get a bit confused. For this example I had to add a method attribute to the service activator element that wouldn't have been needed without the mock.
  • Allways set a timeout. You don't want the test to run eternally on your build server if you are unfortunate enough to break it.

Source code for this example can be found on github. Enjoy!

  • Share/Bookmark

Filed under Java, Opensource, Spring, TDD | 4 Comments »



4 Responses to “Latching and mocking in concurrent tests”



    David Says:
    Posted at: November 3, 2009 at 9:16 pm

    Latches are definitely useful in many situations. May I point you to a, in my opinion, related blog entry by Uncle Bob: http://blog.objectmentor.com/articles/2009/10/28/manual-mocking-resisting-the-invasion-of-dots-and-parentheses
    Personally I tend to lean toward using mocks, but I don’t think there’s any right way. As always, it’s about using the right tool for the right job.



    Andrew Phillips Says:
    Posted at: November 3, 2009 at 11:31 pm

    Another interesting – if somewhat old – option for concurrent testing is Multithreaded TC; there have also been some recent efforts to integrate it with JUnit 4.
    That said, I haven’t found a nice way to get it to do what your example does – provide a latch or delay within the flow of the code under test (in your example, in a mock). MTC is great in coordinating test threads but otherwise assumes that the code under test “naturally” blocks, e.g. when doing a take from a blocking queue.



    Andrew Dinn Says:
    Posted at: November 5, 2009 at 10:18 am

    You might also take a look at Byteman, a bytecode injection tool which was developed to address testing of multi-threaded apps. It makes this sort of thing trivial to achieve and avoids the need for mocking.

    Take a look at my paper in this year’s Jazoon for an example of how to inject a synchronization point into a multi-threaded program, thereby exposing a concurrency bug. It requires a few lines of Byteman rule code and, more importantly, no edits to the original program. Countdowns are also provided as standard built-in operations. They can be used in Byteman conditions to decide whether or not to execute injected actions. Combined with a rendezvous action this can be used to ensure that threads synch up at the NTH call.



    Iwein Fuld Says:
    Posted at: November 12, 2009 at 1:11 pm

    I’m not a mock fanboy, but neither am I allergic to them like Uncle Bob.

    Byteman seems like a very interesting tool to test the concurrent nature of your program, whereas my trick merely allows you to deal with concurrency in a functional test. I’d say usually a trick like this is enough, but if you’re chasing after concurrency bugs it pays off to look a little further.



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    fitnesse Groovy qcon Closures XML SOA Xebia Lean Agile Awareness Workshop esb JavaOne Introduction to Agile product owner Spring Java Scala Maven Testing Agile Hibernate IntelliJ Architecture Ajax Scrum Poppendieck Performance Functional Programming Grails Semantic Web Seam
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs