频道
bg

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 主要实现TestTemplateInvocationContextProviderprovideTestTemplateInvocationContexts 方法

java

@Override
public 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() {
@Override
public String getDisplayName(int invocationIndex) {
return userIdGeneratorTestCase.getDisplayName();
}
@Override
public List<Extension> getAdditionalExtensions() {
return asList(
new GenericTypedParameterResolver(userIdGeneratorTestCase),
new BeforeTestExecutionCallback() {
@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
System.out.println("BeforeTestExecutionCallback:Disabled context");
}
},
new AfterTestExecutionCallback() {
@Override
public void afterTestExecution(ExtensionContext extensionContext) {
System.out.println("AfterTestExecutionCallback:Disabled context");
}
}
);
}
};
}

数组中包含实例

  • GenericTypedParameterResolver 参数Resolver
  • BeforeTestExecutionCallback 测试方法执行前的回调用
  • AfterTestExecutionCallback 测试方法执行后的回调用
  • DisabledOnQAEnvironmentExtension 不执行测试方法

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.