gpt4 book ai didi

java - 无需应用程序测试 Spring/Spring Boot

转载 作者:行者123 更新时间:2023-12-02 03:27:14 25 4
gpt4 key购买 nike

我想编写必须使用 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=...)”的配置?那我需要什么样的配置类呢?

最佳答案

我刚刚遇到问题,让我回到开头;首先添加一个配置类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扩展你的测试类名称。

关于java - 无需应用程序测试 Spring/Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com