Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Couchbase

I have a Java based data access layer that interacts with Couchbase. In order to apply unit testing to this layer I would like to mock Couchbase.

Browsing the net I encountered this project which is also hosted in GitHub. I would like to use it but missing some basic examples.

Maybe someone has tried it before and can provide me with some basic usages in Java?

like image 878
forhas Avatar asked May 14 '14 07:05

forhas


1 Answers

Personally when testing Couchbase using unit tests I don't use either of those projects, I just use Mockito to mock out the Couchbase calls.

Ideally all your calls to Couchbase are nicely encapsulated into DAO's. Mockito allows me to return what I expect in terms of json payloads etc but at the same time I can simulate timeout and other exceptions.

As a simple example where you are checking what happens if Couchbase throws an exception during an add operation you'd do the following (I expect a runtime exception as I catch the earlier exception and rethrow due to it being non recoverable for this example):

@Test(expected = RuntimeException.class)
public void testSaveUserFailsOnAddDueToTimeout() {
    when(couchbase.incr(anyString(), anyInt())).thenReturn(0L);
    when(couchbase.add(anyString(), anyObject())).thenThrow(InterruptedException.class);
    this.userDao.saveUser(SOURCE);
}

You can view the whole test class here:

https://github.com/scalabilitysolved/couchbase-java/blob/master/src/test/java/com/scalabilitysolved/couchbase/dao/UserDaoTest.java

Or the whole project here (which is a simple Couchbase/Spring/API example)

https://github.com/scalabilitysolved/couchbase-java

like image 184
scalabilitysolved Avatar answered Nov 19 '22 18:11

scalabilitysolved