Thursday, 15 July 2010

java - Mocking method chaining with Mockito (especially a JPA TypedQuery) -



java - Mocking method chaining with Mockito (especially a JPA TypedQuery) -

i have lot of code sample below need test mockito.

return entitymanager .createnamedquery("queryname", type.class) .setparameter("foo", "fish") .setparameter("bar", 42) .getsingleresult();

i have injected mocked entitymanager , have homecoming mocked typedquery, etc. problem need specify rule next every method in typedquery in order have test run without nullpointerexceptions.

when(mockedtypedquery.setparameter(any(string.class), any(object.class))) .thenreturn(mockedtypedquery);

is there more efficient way?

what did in case, totally inspired post: http://geeks.autotrader.co.uk/2014/03/mocking-fluent-interfaces-with-mockito.html

i had next service:

public class testservice { public typedquery typedquery; public list test(){ final typedquery typedquery1 = typedquery.setparameter("a", "a"); homecoming typedquery1.setparameter("b", "b").getresultlist(); } }

and test case was:

@runwith(mockitojunitrunner.class) public class chainmethodsmocktest { typedquery mockedtypedquery = fluentmock(typedquery.class); @injectmocks testservice testservice; @test public void testmockito(){ final arraylist value = new arraylist(); value.add("a"); value.add("b"); mockito.when(mockedtypedquery.getresultlist()).thenreturn(value); final list test = testservice.test(); assert.assertequals(2, test.size()); } public static <t> t fluentmock(final class<t> type) { homecoming mockito.mock(type, mockito.withsettings().defaultanswer( new returnsemptyvalues() { @override public object answer(invocationonmock invocation) { object defaultreturnvalue = super.answer(invocation); if (type.equals(invocation.getmethod().getreturntype())) { homecoming invocation.getmock(); } else { homecoming defaultreturnvalue; } } })); } }

fluentmock method can share , reuse among project(s).

java unit-testing jpa mockito

No comments:

Post a Comment