单元测试未初始化

时间:2017-08-10 15:44:40

标签: java unit-testing junit springrunner

在我的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>

我在下面的课程中有一个方法需要测试:

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

然后测试类是:

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

1 个答案:

答案 0 :(得分:0)

您的测试类应注明:

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

此JUnit运行器需要JUnit版本&gt; = 4.12。您对spring-boot-starter-test的依赖将带来所需的JUnit版本,因此您可以删除对JUnit的依赖。您对JUnit 4.11的explcit依赖性与Spring runner的JUnit期望发生冲突。