Spring Boot 启动不连接数据库和Spring Boot Junit

如果你希望试一试那么直接复制运行,如果你先更进一步了解就仔细看看代码,花上5-30分钟然后可以重新应该能理解。然后就自己结合自己需求改改吧。
如果你创建一个全新的springboot项目直接启动会报错Failed to configure a DataSource
错误提示为:

***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

如果期望不添加数据库那么久在启动类上添加:
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
启动类全文为:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class TestComponentsApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestComponentsApplication.class, args);
    }
}

springboot Junit
POM.xml添加

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

单独的Junit测试示例

import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SpringBootJunitTest {
    @Test
    public void springbootTest() {
        System.out.println("JunitTest");
    }
}

Spring环境Junit测试示例

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.Components.demo.TestComponentsApplication;

@SpringBootTest(classes=TestComponentsApplication.class)
@RunWith(SpringRunner.class)
public class SpringBootJunitTest {
    //读取配置文件参数
    @Value("${junit.junitTest}")
    String junitTests;  
    @Test
    public void springbootTest() {
        System.out.println("JunitTest:"+junitTests);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容