The correct way to check with Mockito

I have a method - getSomethingAmount () in some class (class A) that I want to check. This getSomethingAmount () method depends on Set bSet, which is passed in the constructor when class A is initialized. For example, if Set bSet contains 2 objects with Status.OK, when getSomethingAmount () should return 2. How can I correctly check this condition using Mokito ?

Now I create objects of class class B 2, put them in bSet, and then assert the result of getSomethingAmount () with the statement of JUnit - it works, but it does not look to me like the “true” Mockito way.

+4
source share
2 answers

From your description of the expected behavior, this seems like a pretty solid way of unit test method. Under the “true Mockito way,” I suggest that you want something like:

Set mockBSet = mock(Set.class); stub(mockBSet.size()).toReturn(2); A testObjectA = new A(mockBSet); Assert.assertEquals(testObjectA.getSomethingAmount(), 2); 

This assumes that initializing the Set and test objects does not have any side effects that you want the test to take into account. (For example, it always adds some default "somethings"). In this case, you can also ignore stubbing and claim that the tested method returns a value equal to the size of the set.

+1
source

Select objects in collections, not collections. Otherwise, the test will be fragile and break if you change the implementation. For example, if you decide that you need to scroll through the objects in the set, and not just use the size method.

 B b = mock(B.class); A target = new A(new HashSet<B>(Arrays.asList(b, b))); Assert.assertSame(2, target.getSomethingAmount()); 
+1
source

Source: https://habr.com/ru/post/1342771/


All Articles