javaunit-testingjunitspringrunner

Unit tests is not initialized


In my spring boot application, I have the following dependencies:

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>1.5.2.RELEASE</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

I have a method in the below class which i need to test:

@Service
public class DataExtractorService {

    @Autowired
    LinksWriterService writer;

    Kinkester kinkester;

    public DataExtractorService(){
        kinkester=new Kinkester();
    }

    public Kinkester extractor(String rowData){
          String pattern = "(\\d+)(\\D*)";

          Pattern r = Pattern.compile(pattern);

          Matcher m = r.matcher(rowData);
          if (m.find( )) {
             System.out.println("Found value: " + m.group(0) );
             System.out.println("Found value: " + m.group(1) );
          }else 
              System.out.println("NO MATCH");
          kinkester.setAge(Integer.parseInt(m.group(0)));
          kinkester.setRole(m.group(1));

        return kinkester;
    }
}

and then the test class is:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SeleniumApplication.class)
@WebAppConfiguration

public class DataExtractorTest {


    @Autowired
    DataExtractorService dataExtractorService;

    @Test
    public void extractor(){
        Kinkester kinkester = dataExtractorService.extractor("45M");
        System.out.println(kinkester.getAge());
        //assertEquals(kinkester.getAge(),45);

    }       
}

But unfortunately the test does not run. it complains with

Initialization Error (Runner: Junit 4 )

I have tried the below code, but still no answer got:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SeleniumApplication.class})

Solution

  • Your test class should be annotated with:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = SeleniumApplication.class)
    

    This JUnit runner requires JUnit version >= 4.12. Your dependency on spring-boot-starter-test will bring the required version of JUnit in transitively so you can remove the dependency on JUnit. Your explcit dependency on JUnit 4.11 is clashing with the Spring runner's JUnit expectations.