Monday, June 3, 2019

Unit testing with jUnit5 and Mockito

Mocking for Spring injected dependencies

import org.junit.jupiter.api.Test;

@ExtendWith(MockitoExtension.class)
class Person {
   @Mock
   DependencyA dependencyA;

   // Don't use @InjectMocks if using constructor injection with final dependencies.
   // Mockito can't set the new mocks for each test
   TestedClass target;

   @BeforeEach
   public void setup() {
      // only needed if you do Mockito.when(dependencyA.methodAbc()).thenReturn() or similar
      MockitoAnnotations.initialize(this);  
      target = new TestedClass(dependencyA);
   }

   @Test
   public void testMethodWhatsyourname() {
      // given
      ...
      
      // when
      target.whatsYourName();

      // then 
      ...
   }
}

No comments: