Psycho Punch
Psycho Punch

Reputation: 6902

How do I exclude Repositories in Spring tests?

I'm writing tests for a Controller that uses a CrudRepository. Typically, I'd like to isolate the unit test by using mocks instead of the actual repository instances. However, Spring keeps injecting actual Repository proxies, and I don't know how to effectively exclude them.

My unit test look something like:

@SpringApplicationConfiguration(TestConfiguration)
@WebAppConfiguration
class ControllerSpec extends Specification {
    ...
}

The configuration looks like:

@Configuration
@ComponentScan
@EnableAutoConfiguration
class TestConfiguration {

    @Bean
    AccountRepository accountRepository() {
        mock(AccountRepository)
    }

}

I've tried annotating the configuration class with @NoRepositoryBean but it didn't work. I also tried using excludeFilters in ComponentScan using regex type, but it also didn't work.

Upvotes: 3

Views: 4243

Answers (2)

Psycho Punch
Psycho Punch

Reputation: 6902

@EnableAutoConfiguration annotation has an excludes property that allows users to ignore some auto-configuration features. Most of these are represented by corresponding *AutoConfiguration classes. To bypass repositories in particular, the following can be excluded from auto-configuration:

  • HibernateJpaAutoConfiguration
  • DataSourceAutoConfiguration
  • JpaRepositoriesAutoConfiguration

I'm not really sure which combination of them is the absolute minimum, but it should be relatively easy to do trial-and-error with them.

Upvotes: 1

dogankadriye
dogankadriye

Reputation: 538

You need to use @InjectMock annotation at the top of your controller and @Mock annotation for your repository.

@RunWith(MockitoJUnitRunner.class)
public class AccountControllerTest {

@InjectMocks
AccountController controller;

@Mock
AccountRepository accountRepository;
}

Upvotes: 0

Related Questions