Spring开机测试配置 [英] Spring boot test configuration
本文介绍了Spring开机测试配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 spring boot 应用程序,主类如下:
I have a spring boot application with main class like below:
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
现在我想测试我的服务并创建了一个基础测试类:
Now I want to test my services and created a base test class:
@SpringApplicationConfiguration(Application.class)
public abstract class TestBase {
}
运行测试时出现异常:
Caused by: java.lang.IllegalArgumentException: Can not load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration.
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:117)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
然后我使用 ContextConfiguration 更改我的基本测试类
Then I change my base test class using ContextConfiguration
@ContextConfiguration(classes = Application.class)
public abstract class TestBase {
}
这次我得到了数据源初始化错误.我想知道为什么它在第一种情况下失败,为什么在第二种情况下它没有加载我配置数据源的 application.properties.
This time I get DataSource initialization error. I am wondering why it is failing in first case and why in second case it does not load my application.properties where I have configured datasource.
谢谢!
推荐答案
类似的东西:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTest{
@Autowired
Foo foo; //whatever you are testing
@Test
public void FooTest() throws Exception{
Foo f = foo.getFooById("22");
assertEquals("9B", f.getCode);
}
//TODO look into MockMVC for testing services
}
这篇关于Spring开机测试配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文