无法使用NULL“contextLoader”构建ApplicationContext。考虑使用@ContextConfiguration注释您的测试类

时间:2017-02-06 22:00:09

标签: java junit

我有一个使用junit的简单测试类。不幸的是,当我想运行测试用例时,它会抱怨。

这是maven:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test</artifactId>
        <version>1.4.3.RELEASE</version>
        <scope>test</scope>
    </dependency>

然后在测试类中:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RestUploaderApplication.class)
public class RestUploaderApplicationTests {

    Station station1;
    Station station2;
    Content content1;
    Content content2;

    ContentRepository contentRepo;
    StationRepository stationRepo;

    @Before
    public void createObjects(){
        Station station1=new Station("UT","Livii 2");
        Station station2=new Station("City Center","Kissing Square");
        Content content1=new Content(station1,"BMW","Text","google.com",10,true);
        Content content2=new Content(station2,"SWB","Image","swb.com",100,true);

    }

    @Test
    public void insertInstancesTest() {
        int size=station1.getContents().size();
        assertEquals(1,size);
    }}

最后,在运行时出现错误:

Exception in thread "main" java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@67b64c45] to prepare test instance  a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
    at org.springframework.util.Assert.notNull(Assert.java:115)

1 个答案:

答案 0 :(得分:0)

我认为@SpringApplicationConfiguration在spring boot 1.4.0中已被弃用。

我不确定但是可以尝试用@SpringApplicationConfiguration替换@SpringBootTest,例如

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RestUploaderApplicationTests {

SpringBootTest应该自动配置你的spring上下文加载器(同时希望重新发送错误: ... instance a NULL'contextLoader'。考虑使用@ContextConfiguration 注释你的测试类)自动配置您的MockMVC(虽然在这种情况下似乎不需要)

顺便说一句,如果这是实际的测试计划,它看起来不像是需要Spring知道的,似乎没有使用任何弹簧组件,(@ Beans / @MockBeans,@ Autowired, @Controllers等)和常规的旧JUnit应该没问题

希望这有帮助

编辑//添加了来源

@SpringApplicationConfiguration docs

@SpringBootTest docs