Search code examples
javaspringunit-testingmockitospring-boot-test

Define common mock objects for many test classes


I'm learning unit testing with Spring Boot. I've created a stub object from Spring Data repository class using Mockito. All works fine, here's a code:

@SpringBootTest
class UserServiceTest {

@MockBean
private UserRepository userRepository;

@BeforeAll
public void  configureMock() {
    User user = new User("mishenev",
            "Dmitrii",
            "Mishenev",
            "123",
            "mishenev.8@gmailcom",
            new UserSettings());
    when(userRepository.findById(anyLong())).thenReturn(Optional.of(user));
    when(userRepository.findUserByUserName(anyString())).thenReturn(user);

 // .. Tests
}

But it's kind of boilerplate style to use this @BeforeAll test repository configuration for each class, if we don't need different stub behaviour. Then i tried to use @TestConfiguration

@TestConfiguration
 public class SpringRepositoryTestConfiguration {

@Bean
public UserRepository userRepository () {
    UserRepository userRepository = Mockito.mock(UserRepository.class);
    // Configuring mock's behaviour
    return userRepository;
    }
}

After that i used

@SpringBootTest(classes = SpringRepositoryTestConfiguration.class)

But i can't using @MockBean to autowire repository in UserService now. I want to understand is it possible to take out and use all test Repository type stubs in one configuration class. Thank you in advance!


Solution

  • Just use this

    class TestConfig {
    
       @Bean
       UserRepository userRepository() {
           final UserRepository repo = mock(UserRepository.class);
           .. do mocking ..
           return repo;
    
       }
    
    }
    
    

    Then you can just @Import(TestConfig.class) where you need it