java - When using Mokito, what is the difference between the actual object and the mocked object? -


in program below, trying use mockito junit in test case. don't see how mokito helping create objects test? don't see special here seems if mokito instantiating object.

   public class testcase1{      @mock      myclass myclass;      public void setup(){         mokitoannotations.initmoks(this);         }        @test        public void testaddition(){           when(myclass.add(2,2)).thenreturn(20);          assertequals(4,myclass.add(2,2));       }    } 

my actual class (myclass.java)

    public class myclass{         public int add(int x, int y){            return x+y;         }     } 

is mocking object, same injecting(di) object? appreciate help!

your test doesn't test of code. tests mockito works fine.

when introduce concept of mocking, take example: suppose build detonator, , want test it. of course use detonator real bomb, , see if whole block explodes when use detonator. isn't practical. btw, maybe don't have bomb @ disposal. maybe colleague still building it.

so use mock bomb. note important point: test detonator, use mock bomb. not mock detonator. mocked dependency of class under test. not class under test itself.

what mock bomb? it's fake bomb doesn't anything. allowing verify if has been asked explode or not. code test detonator this:

// create mock bomb: bomb mockbomb = mock(bomb.class); // create real detonator, tie mock bomb: detonator detonator = new detonator(mockbomb);  // test detonator. since it's tied mock bomb, block // won't explode detonator.presstheredbutton();  // check mock bomb has been asked explode, should  // if detonator works correctly verify(mockbomb).explode(); 

now if test passes, know internal circuitry used in presstheredbutton() works fine , tells bomb explode. know that, when used real bomb, real bomb asked explode when pressing red button.

now let's come real world: want test service, , service uses dao needs database, populated data, run fine. test service, can mock dao, , verify works fine. mock dao can used stub, i.e. object returns tell return in test, instead of querying database. that's you're doing in code in question: you're telling mock myclass instance that, when add() called 2 , 2 arguments, should return 4.

this makes test easier setup, faster run, , independant actual code of dao, not want test in unit test of service.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -