
Junit TestInstance
coding一月 12, 20211mins
Java Test
Test Template 用于测试逻辑类似,只是测试数据不同的场景,代码示例
java
public class UserIdGeneratorImplUnitTest {@TestTemplate@ExtendWith(UserIdGeneratorTestInvocationContextProvider.class)public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) {UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled());String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName());assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId());}}
UserIdGeneratorTestInvocationContextProvider 主要实现TestTemplateInvocationContextProvider 的provideTestTemplateInvocationContexts 方法
java
@Overridepublic Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext extensionContext) {boolean featureDisabled = false;boolean featureEnabled = true;return Stream.of(featureDisabledContext(new UserIdGeneratorTestCase("Given feature switch disabled When user name is John Smith Then generated userid is JSmith",featureDisabled,"John","Smith","JSmith")),featureEnabledContext(new UserIdGeneratorTestCase("Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith",featureEnabled,"John","Smith","baelJSmith")));}
该方法主要返回TestTemplateInvocationContext的实例Stream,有几个实例,测试类就执行几次,相当于测试数据
TestTemplateInvocationContext 的子类主要实现getAdditionalExtensions 方法,返回Extension 数组
java
private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) {return new TestTemplateInvocationContext() {@Overridepublic String getDisplayName(int invocationIndex) {return userIdGeneratorTestCase.getDisplayName();}@Overridepublic List<Extension> getAdditionalExtensions() {return asList(new GenericTypedParameterResolver(userIdGeneratorTestCase),new BeforeTestExecutionCallback() {@Overridepublic void beforeTestExecution(ExtensionContext extensionContext) {System.out.println("BeforeTestExecutionCallback:Disabled context");}},new AfterTestExecutionCallback() {@Overridepublic void afterTestExecution(ExtensionContext extensionContext) {System.out.println("AfterTestExecutionCallback:Disabled context");}});}};}
数组中包含实例
- GenericTypedParameterResolver 参数Resolver
- BeforeTestExecutionCallback 测试方法执行前的回调用
- AfterTestExecutionCallback 测试方法执行后的回调用
- DisabledOnQAEnvironmentExtension 不执行测试方法
评论
新的评论
上一篇
Spring Boot Testing
检测Test Configuration 不像Spring Framework使用的 @ContextConfiguration 来声明主要的Configuration,Spring Boot的 @*Test 注解,如果没有明确定义主要的Configuration的话会自动…
下一篇
Plain JDBC Transaction Manager
要使用Spring的事务管理来处理普通的JDBC调用,不能直接从 Datasource 中获取 Connection ,需要使用 DataSourceUtils.getConnection This transaction manager also supports dire…
