Home

News: Advanced techniques with Mockito

  1. Advanced techniques with Mockito (4 messages)

    When you are writing unit tests, you must keep in mind to not have dependencies to external components. To avoid this we use mock frameworks which for me the easiest one to use is Mockito.

    In this post we are going to see an "advanced" technique used in Mockito to return same argument instance on a mocked method using Answer interface.

    Suppose we are writing unit tests for class which manages Person and Job classes and as operation it uses a DAO class for inserting the relationship class (M:N) between Person and Job called PersonJob.

    Read Full Post

    Threaded Messages (4)

  2. Why?[ Go to top ]

    Why not just return an already mocked instance?

     

    @Mock PersonJob personJob;

    @Test

    public void myTest() {

    PersonJobDao personJobDao = mock(PersonJobDao.class); when(personJobDao.create(any(PersonJob.class))).thenReturn(personJob);

    }

  3. ah, nevermind[ Go to top ]

    Got it now.

  4. Wouldn't it be simpler to write a subclass of PersonJobDao?

    public MockPersonJobDao extends PersonJobDao {

      @Override

      public PersonJob create(PersonJob personJob) {

        return personJob;

      }

    }

     

    Regards,

    Gabriel

  5. It depends[ Go to top ]

    Well depending, it is another strategy too, but I feel more comfortable and maintaing a better readibility because anyone who reads the test, knows exactly what is being mocked and how, meanwhile creating an external helper class, you are forcing the test reader to open another class to see what its behaviour is.