简体   繁体   中英

Mock Beans from Spring Context

I want create tests working with the Spring Context, with mocked Repository beans. I'm using Spring Boot 1.3.2.BUILD-SNAPSHOT + JUnit + Mockito.

Here is my Test config class:

@ComponentScan(basePackages = "myapp", excludeFilters =
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
        value = {
                OfferRepository.class
        }
)
)
@Configuration
public class TestEdge2EdgeConfiguration {

    @Bean
    public OfferRepository offerRepository() {
       return mock(OfferRepository.class);
    }

}

Purpose of this configuration is to exclude OfferRepository from Spring Context and mock it, thank to this I'll be able to write tests who are using Spring Context with mocked database Repository.

Here is my test class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestEdge2EdgeConfiguration.class})
@WebAppConfiguration
public class OfferActionsControllerTest {

    @Autowired
    private OfferRepository offerRepository;

    @Autowired
    private OfferActionsController offerActionsController;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void saveOffer() {
        //given
        BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
        //when
        ResponseEntity<Offer> save = offerActionsController.save(new Offer());

        //then
        org.springframework.util.Assert.notNull(save);
    }
}

Test and test configuration directory is:

src/test/java/myapp 

My application configuration and packages containing OfferRepository directory is:

src/main/java/myapp/

The problem is that Spring Boot is not loading my configuration from TestEdge2EdgeConfiguration.class and mock for OfferRepository is never created.

Can any body help me with this, please?

This is how you should be doing it (Assuming you are writing a test for offerActionsController and injecting offerRepository):

@Mock
private OfferRepository offerRepository;

@InjectMocks
private OfferActionsController offerActionsController;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

You can write your test method as follows:

@Test
public void saveOffer() {
    /* Given */
    Mockito.when(offerRepository.save(Mockito.any(Offer.class))).thenReturn(new Offer());

    //when
    ResponseEntity<Offer> save = offerActionsController.save(new Offer());

    //then
    org.springframework.util.Assert.notNull(save);
}

Use Spingockito to replace the bean with a mock using @ReplaceWithMock . Don't forget to use @Autowired with @ReplaceWithMock if you need access to the mocked bean in the test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM