unit testing - Mocking beans in spring context using Spring Boot -
i'm using spring boot 1.3.2, , notice problem, componentscan in test class not working. , want mock of spring beans. spring boot blocking componentscan?
test config class:
@configuration @componentscan(value = {"myapp.offer", "myapp.image"}) public class testedge2edgeconfiguration { @bean @primary public offerrepository offerrepository() { return mock(offerrepository.class); } } test class:
@contextconfiguration(classes=testedge2edgeconfiguration.class, loader=annotationconfigcontextloader.class) public class offeractionscontrollertest extends abstracttestngspringcontexttests { @autowired private offerrepository offerrepository; @autowired private offeractionscontroller offeractionscontroller; @beforemethod 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); } }
solution of problem
test config class, it's important exclude springbootapplicationconfigutation , add @componentscan:
@componentscan(basepackages = "com.example", excludefilters = @componentscan.filter(type = filtertype.assignable_type, value = {springbootapplicationconfigutation.class, mydao.class} ) ) @configuration public class testedge2edgeconfiguration { @bean public offerrepository offerrepository() { return mock(offerrepository.class); } } and test:
@springapplicationconfiguration(classes=testedge2edgeconfiguration.class) public class offeractionscontrollertest extends abstracttestngspringcontexttests { @autowired private offerrepository offerrepository; @autowired private offeractionscontroller offeractionscontroller; @beforemethod public void resetmock() { mockito.reset(offerrepository); } @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); } }
Comments
Post a Comment