'@MockBean not fluent with testNG

With JUnit i could use @MockBean easily :

    @SpringBootTest(classes = AppConfig.class)
    @RunWith(SpringRunner.class)
    public @Log class ServiceDrhImplTest_JUnit {

        private @Autowired ServiceDrh serviceDrh;
        private @MockBean EmployeDao employeDao;
        private @MockBean SalaireDao salaireDao;

BUT with TestNG it doesn't work out of the box, with the abov syntax, the mocks are null. I have to add @Autowired to @MockBean to make it works. Further more mocks are not reset after each test, i have to had :

    @SpringBootTest(classes = AppConfig.class)
    public @Log class ServiceDrhImplTest_TestNG extends AbstractTestNGSpringContextTests {

        private @Autowired ServiceDrh serviceDrh;
        private @MockBean @Autowired EmployeDao employeDao;
        private @MockBean @Autowired SalaireDao salaireDao;

        @AfterMethod
        public void afterMethod() {
            Mockito.reset(employeDao, salaireDao);
        }

Do you confirm this behavior ? Does it mean that Spring is stopping to support TestNG since it does not appear in spring-boot ref doc anymore ?



Solution 1:[1]

Your issue is already known by Spring and not yet fixed: https://github.com/spring-projects/spring-boot/issues/7689

And even if the documentation of Spring Boot doesn't reference TestNG, it provides a test sample for TestNG: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-testng

Solution 2:[2]

I experienced the same error here in the future now that Spring Boot does support TestNG.

My fix for this was to make sure my test class extends AbstractTestNGSpringContextTests and has the @ContextConfiguration annotation

@ContextConfiguration(classes = {ClockConfig.class, UtilDate.class})
public class UtilDateTest extends AbstractTestNGSpringContextTests {
   @Inject
   @MockBean
   Clock clock;

   @Inject
   UtilDate utilDateUnderTest;

   @Test
   public void testUtilDate() {
       // mock clock
       // test utilDateUnderTest
   }
}
@Configuration
public class ClockConfig {

    @Bean
    public Clock clock() { ... }
}

@Named
public class UtilDate
{
    @Inject
    private Clock clock;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juherr
Solution 2 Eric Riese