unit testing - Mock Beans from Spring Context -


i want create tests working spring context, mocked repository beans. i'm using spring boot 1.3.2.build-snapshot + junit + mockito.

here 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 configuration exclude offerrepository spring context , mock it, thank i'll able write tests using spring context mocked database repository.

here 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 , test configuration directory is:

src/test/java/myapp  

my application configuration , packages containing offerrepository directory is:

src/main/java/myapp/ 

the problem spring boot not loading configuration testedge2edgeconfiguration.class , mock offerrepository never created.

can body me this, please?

this how should doing (assuming writing test offeractionscontroller , injecting offerrepository):

@mock private offerrepository offerrepository;  @injectmocks private offeractionscontroller offeractionscontroller;  @before public void setup(){     mockitoannotations.initmocks(this); } 

you can write test method 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); } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -