无应用程序测试Spring / SpringBoot

时间:2017-12-01 11:30:31

标签: java spring unit-testing spring-boot spring-test

我想编写必须使用Spring Framework和自定义JPA提供程序的集成测试。我认为将直接回答创建一个测试类并按如下方式对其进行注释:

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

希望所有默认的自动配置都需要自行完成。但它不是错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

我可以避免创建:

@SpringBootApplication
public class TestApp { ...

并且只使用src / test / java文件夹并提供“@SpringBootTest(classes = ...)”的配置?那我需要什么样的配置类?

1 个答案:

答案 0 :(得分:0)

我刚刚遇到问题让我回到开始; 首先添加一个配置类ApplicationContainer

public final class ApplicationContainer {
private static volatile ApplicationContainer singleton;
private ApplicationContext context;
private ApplicationContainer()
{
}

public static ApplicationContainer getInstance()
{
    if(ApplicationContainer.singleton == null)
    {
        synchronized(ApplicationContainer.class)
        {
            if(ApplicationContainer.singleton == null)
            {
                ApplicationContainer.singleton = new ApplicationContainer();
            }
        }
    }
    return ApplicationContainer.singleton;
}

public void setApplicationContext(ApplicationContext context)
{
    this.context = context;
}

public <T> T getBean(Class<T> requiredType)
{
    if(this.context == null)
    {
        throw new IllegalStateException("ApplicationContainer is not started");
    }
    return this.context.getBean(requiredType);
}

public void start()
{
    if(this.context == null)
    {
        this.context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
    }
}

public void stop()
{
    if(this.context == null)
    {
        return;
    }

    if(this.context instanceof AnnotationConfigApplicationContext)
    {
        ((AnnotationConfigApplicationContext)this.context).close();
    }
    this.context = null;
}

@Configuration
@ComponentScan("com.domain.package")
public static class ApplicationConfig
{
    }}    

并改变你的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ApplicationContainer.ApplicationConfig.class})
public class YourTestIT {
@Autowired
private ApplicationContext applicationContext;
@Before
public void up() {
    ApplicationContainer.getInstance().setApplicationContext(this.applicationContext);
}
@After
public void down() {
    ApplicationContainer.getInstance().stop();
}
//test cases
}

然后您可以@Autowired您的存储库类并直接使用,您也应该添加IT扩展您的测试类名。