0
votes

I have very simple SpringBoot Junit but it keeps failing.

@RunWith(SpringRunner.class)
//@SpringBootTest
@WebMvcTest(TokenServiceImpl.class)
public class TokenTest {


    @Test
    public void getOauthToken()
    {

        System.out.println( " done test");

    }

my TokenServiceImpl class has

public class TokenServiceImpl implements TokenService{
public String  getToken() throws RuntimeException{
          return  " Token returned"  ;  
    }

I get the below error : -Snippet

2019-11-27 19:12:45.884 WARN 15864 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'runApplication': Unsatisfied dependency expressed through field 'job'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'job' defined in class path resource [com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]: Unsatisfied dependency expressed through method 'job' parameter 4; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchDBWriter': Unsatisfied dependency expressed through field 'BDREntityRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Field BDREntityRepository in com.mycompany.project1.batch.services.BatchDBWriter required a bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' that could not be found.

Consider defining a bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' in your configuration.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'runApplication': Unsatisfied dependency expressed through field 'job'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'job' defined in class path resource [com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]: Unsatisfied dependency expressed through method 'job' parameter 4; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchDBWriter': Unsatisfied dependency expressed through field 'BDREntityRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchDBWriter': Unsatisfied dependency expressed through field 'BDREntityRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.project1.batch.repositories.BDREntityRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

My main method has following

@SpringBootApplication
@ComponentScan(basePackages= {"com.mycompany.project1"})
public class RunApplication{


    private static final Logger logger = Logger.getLogger(BatchController.class);

    @Autowired 
    JobLauncher jobLauncher;

    @Autowired 
    Job job;

    /*
     * jmxBean will get loaded when this managed bean is called from RMI, and it will fire batch execution
     */
    public static void main(String[] args){

        ApplicationContext app = SpringApplication.run(RunApplication.class, args);
        logger.debug("Batch Application has been started...");
        BatchController controller =    app.getBean(BatchController.class);
        //Start batch process when application starts or restart, its optional call and can be commented out
        //as we have JMX to expose load method on demand
        //BatchController batch = new BatchController();
        controller.startBatchProessFromMain();

    }
}

@Component
public class BatchDBWriter implements ItemWriter<BDREntity> {

    private static final Logger logger = Logger.getLogger(BatchDBWriter.class);

    @Autowired
    private BDREntityRepository bDREntityRepository;

    /*
     * this method call the JPArepository's saveAll
     * function and saves all the list of bdrEntitiesat a time.
     */
    @Override
    public void write(List<? extends BDREntity> bdrEntities) throws Exception {

        bDREntityRepository.saveAll(bdrEntities);
    }
}

How can i fix my Junit ?

1
Annotate with @Component your class BDREntityRepository or delete your @Autowired BDREntityRepository. Either way your are not showing the right information in your question. The problem is not that your test is running incorrectly, the problem is that you have your app wrongly configured for test profile.Federico Piazza
...or extend @ComponsentScan to the package where BDREntityRepository resides.Frischling
BDREntityRepository is under com.mycompany.project1 and is annotated with @Repository. SO thats not problem as i am able to run the application correctly.I am gettin this issue only when launchig Junit.Plus i am using SPRING BATCHRahul
@FedericoPiazza obviously app is wrongly configured for test profile otherwise i won't have asked the questionRahul
@Rahul not "obviously", your question says that your test keep failing which is not correct, your test is not failing at all... your application is not starting. The error your are showing in your question says that you are missing a bean BDREntityRepository for the test profile. It is not related to the test case you put in your question. So, this question is impossible to answer with the information you provided. Simply read the log NoSuchBeanDefinitionException, this means that for your test profile you are missing a bean to be annotated with @ComponentFederico Piazza

1 Answers

2
votes

You are using @WebMvcTest that is a test-slice annotation. It's specifically intended for testing the WebMvc-related components in your application and is a form of integration test.

You've said in the comments that you're not trying to integration test your application. In that case, you should not be using @SpringBootTest or any of the other @…Test annotations that are provided by Spring Boot.

Assuming that your goal is to unit test TokenServiceImpl, I'd expect your test class to look something like this:

public class TokenTest {

    private final TokenServiceImpl tokenService = new TokenServiceImpl();

    @Test
    public void getOauthToken() {
        String token = this.tokenService.getToken();
        // Assertions to check the token go here
    }

}