单元测试未初始化

Unit tests is not initialized

在我的 spring boot 应用程序中,我有以下依赖项:

   <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>

我在下面有一个方法 class 我需要测试一下:

@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;
    }
}

然后测试class是:

@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);

    }       
}

但不幸的是测试没有运行。它抱怨

Initialization Error (Runner: Junit 4 )

我试过下面的代码,但仍然没有得到答案:

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

您的测试 class 应注释为:

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

此 JUnit 运行程序要求 JUnit 版本 >= 4.12。您对 spring-boot-starter-test 的依赖将传递所需的 JUnit 版本,因此您可以删除对 JUnit 的依赖。您对 JUnit 4.11 的明确依赖与 Spring 参赛者对 JUnit 的期望发生冲突。