springboot项目创建笔记2 之《junit单元测试》

1、创建测试目录:src/test/java
2、在目录src/test/java下建立测试文件:BootTest.java

package myboot;

import org.junit.After;
import org.junit.Before;
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.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.example.myboot.MybootApplication;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MybootApplication.class) // 指定启动类
@WebAppConfiguration // 由于是Web项目,Junit模拟ServletContext
@TestPropertySource(value = "classpath:test.properties") // 指定测试参数文件
public class BootTest {

	@Value("${key}")
	private String str;

	@Value("${key2}")
	private String str2;

	@Before
	public void init() {
		System.out.println("开始测试-----------------");
	}

	@After
	public void after() {
		System.out.println("测试结束-----------------");
	}

	@Test
	public void testHello() {
		System.out.println("hello world...");
		System.out.println("str is: " + str);
		System.out.println("str2 is: " + str2);
	}
}

3、在application.properties加入

key2=1111111111

4、在src/test/resources下建立test.properties

key=1234567890

5、执行测试testHello

18:06:19.357 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class myboot.BootTest]
18:06:19.361 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
18:06:19.368 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
18:06:19.384 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [myboot.BootTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
18:06:19.395 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [myboot.BootTest], using SpringBootContextLoader
18:06:19.398 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [myboot.BootTest]: class path resource [myboot/BootTest-context.xml] does not exist
18:06:19.399 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [myboot.BootTest]: class path resource [myboot/BootTestContext.groovy] does not exist
18:06:19.399 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [myboot.BootTest]: no resource found for suffixes {-context.xml, Context.groovy}.
18:06:19.435 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [myboot.BootTest]
18:06:19.537 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [myboot.BootTest]: using defaults.
18:06:19.538 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
18:06:19.546 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
18:06:19.547 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
18:06:19.547 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@11dc3715, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@69930714, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@7a52f2a2, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@78047b92, org.springframework.test.context.support.DirtiesContextTestExecutionListener@8909f18, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@79ca92b9, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@1460a8c0, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4f638935, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@4387b79e, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@6e75aa0d]
18:06:19.548 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.548 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.549 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.549 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.556 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.556 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.557 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.557 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.557 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.558 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.560 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@233fe9b6 testClass = BootTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@358ee631 testClass = BootTest, locations = '{}', classes = '{class com.example.myboot.MybootApplication, class com.example.myboot.MybootApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3c0f93f1, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@31610302, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@6c3708b3, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5b87ed94, org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@47ef968d], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
18:06:19.561 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [myboot.BootTest]
18:06:19.561 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [myboot.BootTest]
18:06:19.581 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.8.RELEASE)

2019-10-08 18:06:19.786  INFO 19212 --- [           main] myboot.BootTest                          : Starting BootTest on DESKTOP-PB5DAU8 with PID 19212 (started by User in D:\workspace\study\myboot)
2019-10-08 18:06:19.786  INFO 19212 --- [           main] myboot.BootTest                          : No active profile set, falling back to default profiles: default
2019-10-08 18:06:21.069  INFO 19212 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-08 18:06:21.214  WARN 19212 --- [           main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2019-10-08 18:06:21.383  INFO 19212 --- [           main] myboot.BootTest                          : Started BootTest in 1.791 seconds (JVM running for 2.347)
开始测试-----------------
hello world...
str is: 1234567890
str2 is: 1111111111
测试结束-----------------
2019-10-08 18:06:21.571  INFO 19212 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

6、注解说明
1)@RunWith
引入JUnit4测试框架类,这里的类是SpringRunner,它继承了SpringJUnit4ClassRunner,没有扩展任何功能,是一个简短的别名
2)@SpringBootTest
指定运行Spring Boot环境的测试类,其中classes属性指定了启动类
3)@WebAppConfiguration
注解在类上,用来声明加载的ApplicationContext是一个WebApplicationContext,它的属性指定的是Web资源的位置,默认为src/main/webapp
4)@TestPropertySource
指定测试的资源文件,测试时的查找顺序是先到指定的test.properties中找,然后在从全局文件application.properties中找
7、参考资料
Spring 注解学习笔记:https://www.cnblogs.com/jianliang-Wu/p/5652629.html

注:最新代码上传至https://github.com/csj50/myboot
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值