testing - Mockito mocking method with class parameter vs actual object parameter -


what difference between these 2 per mockito -

mockito.when(serviceobject.mymethod(customer.class)).thenthrow(new runtimeexception());

and

customer customer = new customer(); mockito.when(serviceobject.mymethod(customer)).thenthrow(new runtimeexception());

and if both serve same purpose using 1 considered best practice?

there misunderstanding on side - method specification mymethod(someclass.class) possible when signature of method allows class parameter. like:

whatever mymethod(object o) { 

or directly

whatever mymethod(class<x> clazz) { 

in other words: not mockito special parameter happens of class class!

thus first option not works "in general". example: put down code in unit test:

static class inner {     public int foo(string s) { return 5; } }  @test public void testinner() {     inner mocked = mock(inner.class);     when(mocked.foo(object.class)).thenreturn(4);     system.out.println(mocked.foo("")); } 

and guess - above not compile. because foo() doesn't allow class parameter. can rewrite to

static class inner {     public int foo(object o) { return 5; } }  @test public void testinner() {     inner mocked = mock(inner.class);     when(mocked.foo(object.class)).thenreturn(4);     system.out.println(mocked.foo("")); } 

and now above compiles - prints 0 (zero) when invoked. because above same mocked.foo(eq(object.class)). in other words: when method signature allows passing class instance , pass class instance, simple mocking specification mockito. in example: when incoming object object.class - 4 returned. incoming object "" - therefore mockito default kicks in , 0 returned.

i other answer here - think mixing older versions of mockito asked write down when(mocked.foo(any(expectedclass.class))) - can nowadays written when(mocked.foo(any())). when(mocked.foo(expectedclass.class)) not mockito construct - simple method specification gives specific object "match on" - , specific object happens instance of class class.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -