Spring Boot 测试配置

新手上路,请多包涵

我有一个 spring boot 应用程序,其主类如下所示:

 @SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

现在我想测试我的服务并创建一个基础测试类:

 @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 更改我的基础测试类

@ContextConfiguration(classes = Application.class)
public abstract class TestBase {
}

这次我得到数据源初始化错误。我想知道为什么它在第一种情况下失败,为什么在第二种情况下它不加载我配置数据源的 application.properties

谢谢!

原文由 sansari 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
1 个回答

像这样的东西:

 @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
}

原文由 Mike3355 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题