mohsen dorparasti
mohsen dorparasti

Reputation: 8415

how to unit testing cache layer

I have added a cache layer to my project . now I wonder if I could unit test methods that manipulate cache ? or is there a better way to test Layer's logic ?

I just want to check the process , for example :

1- when the item is not in the cache , method should hit the database

2- the next time method should use cache

3- when a change is made to database , cache should be cleared

4- if data retrieved from databse is null , it shouldn't be added to cache

I want to ensure that the logic I have placed into the methods are working as expected .

Upvotes: 6

Views: 6548

Answers (1)

Finglas
Finglas

Reputation: 15709

I'm presuming the cache is a third party cache? If so, I would not test it. You're testing someone else's code otherwise.

If this caching is so important you need to test it, I'd go with an integration or acceptance test. In other words, hit the page(s)/service(s) in question and check the content that way. By the very definition of what you wish to test, this is not a unit test.

On the flip side, if the cache is one you've rolled yourself, you'll easily be able to unit test the functionality. You might want to check out verification based testing in order to test the behavior of the cache, as apposed to actually checking stuff is added/removed from the cache. Check out mocking for ways to achieve this.

To test for behaviour via Mock objects (or something similar) I'd do the following - although your code will vary.

class Cacher
{
    public void Add(Thing thing) 
    {
         // Complex logic here...
    }

    public Thing Get(int id) 
    { 
        // More complex logic here...
    } 
}

void DoStuff() 
{
   var cacher = new Cacher();
   var thing = cacher.Get(50);
   thing.Blah();
}

To test the above method I'd have a test which used a mock Cacher. You'd need to pass this into the method at runtime or inject the dependency into the constructor. From here the test would simply check that cache.Get(50) is invoked. Not that the item is actually retrieved from the cache. This is testing the behavior of how the cacher should be used, not that it is actually caching/retrieving anything.

You could then fall back to state based testing for the Cacher in isolation. E.g you add/remove items.

Like I said previously, this may be overkill depending on what you wish to do. However you seem pretty confident that the caching is important enough to warrant this sort of testing. In my code I try to limit mock objects as much as possible, though this sounds like a valid use case.

Upvotes: 4

Related Questions