JUnit Platform Launcher使用Injected Spring Beans启动TestClass

时间:2018-03-07 11:21:32

标签: spring junit junit5

我尝试使用JUnit Platform Launcher运行一个测试类。 Testclass包含一些@Autowired组件。问题是,注射似乎不起作用。甚至可以使用JUnit平台吗? 我的代码如下:

App.java

@SpringBootApplication(scanBasePackages = "com.mytests")
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

组件

import org.springframework.stereotype.Component;

@Component
public class SomeBean {

  public String returnSuccess() {
    return "SUCCESS";
  }

}

识别TestClass

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTests {

  @Autowired
  private SomeBean aBean;

  @Test
  public void testSuccess() throws Exception {
    String result = aBean.returnSuccess();
    assertTrue(result.equals("SUCCESS"));
  }

}

调用测试类的控制器

@RestController
public class TestController {

  @RequestMapping("/tests")
  public void executeTests() throws Throwable {

    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
        .selectors(selectPackage("com.mytests"), selectClass(SomeTests.class))
        .build();

    Launcher launcher = LauncherFactory.create();

    SummaryGeneratingListener listener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(listener);
    launcher.execute(request);
    listener.getSummary();
  }

}

0 个答案:

没有答案