Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing test case for Loading Cache guava

I am trying to test the asynchronous loading of cache over my database. I am using Google guava loading cache, which in turn uses Cache loader refreshing the given key asynchronously (as explained in https://code.google.com/p/guava-libraries/wiki/CachesExplained)

I was trying the following steps to test

  • The refresh duration : 1sec
  • Make a call to cache, key is absent. Call to the mock DB is made
  • Thread.sleep(2000L)
  • Make another call for same key. Since the key is present and refresh period is over, the stale value should be returned and async refresh should be kicked off
  • Thread.sleep(2000L)

  • Make another call for the same key.

Since I am mocking the dao, I expect it to be called atleast twice. However, when I am trying to verify the mock, it fails saying that mock was just called once. How do I ensure the dao is called twice? I am mocking the Thread Factory, while creating Executor which is being called for creating a new thread, as expected. Why is the second call to dao never made? Am I missing anything here? I am using new FixedThread Pool executor and decorating it as listening decorator.

What is the right way to test such refreshing caches? Any help is much appreciated.

like image 575
u07103 Avatar asked May 17 '26 07:05

u07103


1 Answers

Use

CacheBuilder.ticker(youtTicker)

and pass a FakeTicker to advance the time at will.

Unless you really want to test the multithreaded behavior, forget threads and test it synchronously.

Look at the source code of e.g., CacheRefreshTest.

Maybe you can spot the problem by simplifying your test... that's all I can say without your exact code.

like image 195
maaartinus Avatar answered May 18 '26 20:05

maaartinus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!