SquareTest实体类模板

Quick Settings - configure common code style and other settings here. -----------------------------------------------

Set these to use special prefixes for test class members containing dependencies of certain types.

Note that the template code below will ignore any prefix set to “” and use your IDE code style settings instead.

#set(KaTeX parse error: Expected 'EOF', got '#' at position 34: …mePrefix = "") #̲set(mockDependencyMemberNamePrefix = “mock”)

Set this to use a special prefix for local fields containing arguments for test methods.

#set(KaTeX parse error: Expected 'EOF', got '#' at position 37: …mePrefix = "") #̲set(mockParameterLocalFieldNamePrefix = “mock”)

Customize the name of the member and local field (if needed) used to store the instance of the source class.

#set( s o u r c e C l a s s . t e s t C l a s s M e m b e r N a m e = " sourceClass.testClassMemberName = " sourceClass.testClassMemberName="{sourceClass.testClassMemberName}UnderTest")
#set( s o u r c e C l a s s . t e s t C l a s s L o c a l F i e l d N a m e = " sourceClass.testClassLocalFieldName = " sourceClass.testClassLocalFieldName="{sourceClass.testClassLocalFieldName}UnderTest")
#set($shouldUseMockitoExtension = $ClassUtils.isInTestClasspath(‘org.mockito.runners.MockitoJUnitRunner’) || C l a s s U t i l s . i s I n T e s t C l a s s p a t h ( ′ o r g . m o c k i t o . j u n i t . M o c k i t o J U n i t R u n n e r ′ ) ∣ ∣ ! ClassUtils.isInTestClasspath('org.mockito.junit.MockitoJUnitRunner') || ! ClassUtils.isInTestClasspath(org.mockito.junit.MockitoJUnitRunner)∣∣!ClassUtils.isInTestClasspath(‘org.mockito.Mockito’))
#set($shouldUseMockitoBdd = false)

Configure how Bean DTOs are initialized.

#set(KaTeX parse error: Expected 'EOF', got '#' at position 33: …nitDepth = 10) #̲set(maxNumberOfSettersToCallPerClass = 10)
#set(KaTeX parse error: Expected 'EOF', got '#' at position 32: …rsToCall = 70) #̲set(useStaticImportForInitMocks = true)

Set this to use mocks for mockable method parameters that end in “listener” or “callback” ignoring case.

#set(KaTeX parse error: Expected 'EOF', got '#' at position 50: …meters = true) #̲set(generateStubsAndVerifyStatements = true)

Use this to specify custom initialization values for dependencies and method parameters of certain types;

See https://squaretest.com#template_api_quick_settings for details.

#set($initExpressionOverrides = {} )
##----------------------------------------------------------------------------------------------------------------------

Initialize the data model. This sets global variables based on the architype of the source class and Quick Settings.

See the comments above the macro or https://squaretest.com#template_api_initializeTemplateDataModel for details.

#initializeTemplateDataModel()

Package declaration

#if( S t r i n g U t i l s . i s N o t E m p t y ( StringUtils.isNotEmpty( StringUtils.isNotEmpty(sourceClass.packageName))
package $sourceClass.packageName;
#end

Imports; Note that Squaretest invokes IntelliJ’s import organize and code reformatter after creating the test class.

#foreach($importLine in $importLinesRequired)
KaTeX parse error: Expected 'EOF', got '#' at position 12: importLine #̲end #if(useStaticImportForInitMocks)
import static org.mockito.MockitoAnnotations.KaTeX parse error: Expected 'EOF', got '#' at position 101: …o.Mockito.spy; #̲end import java…hasAssertThrows)
import static org.junit.Assert.assertThrows;
#end
#renderImportsForMatchers()
#if($shouldUseMockitoBdd)
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.BDDMockito.willReturn;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.BDDMockito.then;
import static org.mockito.BDDMockito.given;
#else
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#end
import KaTeX parse error: Expected 'EOF', got '#' at position 296: …ubbing.Answer; #̲if(springController)
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.mock.web.MockMultipartFile;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
#end

Test class

#renderTestClassAnnotationsIfNeeded()
public class s o u r c e C l a s s . n a m e T e s t e x t e n d s B a s e V o E n t i t y T e s t < {sourceClass.name}Test extends BaseVoEntityTest< sourceClass.nameTestextendsBaseVoEntityTest<{sourceClass.name}>{

@Override
protected ${sourceClass.name} getT() {
    return new ${sourceClass.name}();
}


#renderMockMvcDeclarationIfNeeded()

## Declare member fields for the dependencies.

#renderMemberDeclarations(KaTeX parse error: Expected 'EOF', got '#' at position 23: …berFields) #̲renderMemberDec…nonMockMemberFields)

## Declare a member field for the instance of the source class.

#if(KaTeX parse error: Expected 'EOF', got '#' at position 34: …eeded) #̲if(shouldUseInjectMocks) @InjectMocks #end
private ${sourceClass.type.canonicalText} ${sourceClass.testClassMemberName};
#end

#if(KaTeX parse error: Expected 'EOF', got '&' at position 13: mocksNeeded &̲& !shouldUseMockitoExtension && !$springController && $hasOpenMocksMethod)
private AutoCloseable mockitoCloseable;
#end

Render setUp() only if we need to instantiate source class.

#if(KaTeX parse error: Expected 'EOF', got '&' at position 25: …ssMemberNeeded &̲& !(shouldUseInjectMocks && KaTeX parse error: Expected '}', got '#' at position 104: … { #̲if(mocksNeeded && !KaTeX parse error: Expected 'EOF', got '#' at position 44: … #̲set(initMocksQualifier = "#if(!KaTeX parse error: Expected 'EOF', got '#' at position 48: …itoAnnotations.#̲else#end") …hasOpenMocksMethod)
mockitoCloseable = i n i t M o c k s Q u a l i f i e r {initMocksQualifier} initMocksQualifier{initMocksMethodName}(this);
#else
i n i t M o c k s Q u a l i f i e r {initMocksQualifier} initMocksQualifier{initMocksMethodName}(this);
#end
#end

Initialize the non-mock member fields.

#foreach($field in $nonMockMemberFields)
$field.testClassMemberName = $field.initExpression;
#end

Initialize the member containing the source class.

#if(KaTeX parse error: Expected 'EOF', got '#' at position 23: …seInjectMocks) #̲# Do nothing. …sourceClass.preferredConstructor)
## Invoke the constructor.
KaTeX parse error: Expected 'EOF', got '#' at position 41: …berName} = new #̲methodCall(sourceClass.preferredConstructor, true) #if(KaTeX parse error: Expected 'EOF', got '&' at position 22: …Class.abstract &̲& !sourceClass.sealed)KaTeX parse error: Expected 'EOF', got '#' at position 30: …stractClassBody#̲end; …shouldSetPackageLocalFields)
#foreach($field in $dependencies)
s o u r c e C l a s s . t e s t C l a s s M e m b e r N a m e . {sourceClass.testClassMemberName}. sourceClass.testClassMemberName.{field.declaredName} = #if($field.shouldStoreInReference) $field.testClassMemberName #else KaTeX parse error: Expected 'EOF', got '#' at position 22: …initExpression #̲end; …sourceClass.singleton)
${sourceClass.testClassMemberName} = $sourceClass.singletonAccessExpression;
#else

As a fallback, set the member to null and leave a comment.

KaTeX parse error: Expected 'EOF', got '#' at position 90: …/; #̲end } …mocksNeeded && !KaTeX parse error: Expected 'EOF', got '&' at position 27: …ckitoExtension &̲& !springController && $hasOpenMocksMethod)
@After
public void tearDown() throws Exception {
mockitoCloseable.close();
}
#end
#end

Render the test methods.

#if(KaTeX parse error: Expected 'EOF', got '#' at position 46: …thods) #̲renderTestMetho…sourceClass.publicInstanceMethods)
#renderTestMethods(KaTeX parse error: Expected 'EOF', got '#' at position 50: …thods) #̲renderTestMetho…sourceClass.protectedInstanceMethods)
#end
#renderTestMethods(KaTeX parse error: Expected 'EOF', got '#' at position 38: …icMethods) #̲renderTestMetho…sourceClass.packageLocalStaticMethods)
#renderTestMethods($sourceClass.protectedStaticMethods)
}

Macros

Add your own macros here. Newlines between macros will not appear in the generated test class;

Squaretest automatically removes all but 1 newline at the end of the generated test class.

##----------------------------------------------------------------------------------------------------------------------

renderTestClassAnnotationsIfNeeded()

Renders the spring controller test class annotations if needed.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestClassAnnotationsIfNeeded)
#if( s p r i n g C o n t r o l l e r ) @ R u n W i t h ( S p r i n g R u n n e r . c l a s s ) @ W e b M v c T e s t ( springController) @RunWith(SpringRunner.class) @WebMvcTest( springController)@RunWith(SpringRunner.class)@WebMvcTest({sourceClass.canonicalNameOrName}.class)
#elseif($mocksNeeded && s h o u l d U s e M o c k i t o E x t e n s i o n ) @ R u n W i t h ( shouldUseMockitoExtension) @RunWith( shouldUseMockitoExtension)@RunWith({mockitoRunnerName}.class)
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderMockMvcDeclarationIfNeeded()

Renders a MockMvc member field if one is needed.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderMockMvcDeclarationIfNeeded)
#if($springController)
@Autowired
private MockMvc $mockMvcMemberName;
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderMemberDeclarations($fields)

Renders test-class member declarations for the given List.

Param: $fields - the list of variables for which to render declarations.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderMemberDeclarations KaTeX parse error: Expected 'EOF', got '#' at position 13: fields) #̲set(macro.mockAnnotation = "#if(KaTeX parse error: Expected 'EOF', got '#' at position 27: …oller)@MockBean#̲else@Mock#end")…macro.nonMockAnnotation = "#if(KaTeX parse error: Expected 'EOF', got '#' at position 28: …ller)@Autowired#̲else#end") …field in KaTeX parse error: Expected 'EOF', got '#' at position 17: …ields) #̲if(field.shouldBeMocked)
$macro.mockAnnotation
#else
$macro.nonMockAnnotation
#end
private $field.type.canonicalText $field.testClassMemberName;
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderTestMethods($methods)

Renders tests for the given List. This filters out getters/setters and other methods for which tests should

not be rendered.

Param: $methods - the list of methods for which to render tests.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestMethods KaTeX parse error: Expected 'EOF', got '#' at position 14: methods) #̲if(sourceClass.enum)
#set($macro.methodsToUse = KaTeX parse error: Expected 'EOF', got '#' at position 14: methods) #̲else #set(macro.methodsToUse = KaTeX parse error: Expected 'EOF', got '#' at position 70: …bstract')) #̲end #foreach(method in KaTeX parse error: Expected 'EOF', got '#' at position 29: …ToUse) #̲if(hasAssertThrows && KaTeX parse error: Expected 'EOF', got '#' at position 41: …t) #̲renderSimpleTes…method)
#else
#renderTestMethodForPrimaryFlow(KaTeX parse error: Expected 'EOF', got '#' at position 21: …d) #̲renderTestMetho…method)
#end
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderTestMethodForPrimaryFlow($method)

Renders primary flow test case for the given Method.

Param: $method - the method for which to render the test.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestMethodForPrimaryFlow KaTeX parse error: Expected 'EOF', got '#' at position 13: method) #̲renderTestMetho…method, $AltInfo.newValue())
#end

##----------------------------------------------------------------------------------------------------------------------

renderTestMethodsForAltFlows($method)

Renders test for alternate flows for the given method.

Param: $method - the method for which to render alt-flow tests.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestMethodsForAltFlows $method)
## Render tests for exceptions declared by the source method.

Determine if at at least one dependency interaction that we’ve mocked throws an exception.

#set($macro.mockedDIs = m o d e l A t t r i b u t e P r o v i d e r M e t h o d D I s . c o n c a t ( modelAttributeProviderMethodDIs.concat( modelAttributeProviderMethodDIs.concat(method.dependencyInteractions).satisfiedBy(KaTeX parse error: Expected 'EOF', got '#' at position 45: …Mocked'))) #̲set(macro.isControllerMethod = $springController && c o n t r o l l e r M e t h o d s . c o n t a i n s ( controllerMethods.contains( controllerMethods.contains(method))
#set($macro.shouldRenderTestsForIoParams = m e t h o d . s t a t i c ∣ ∣ ( ! method.static || (! method.static∣∣(!macro.isControllerMethod && !(KaTeX parse error: Expected 'EOF', got '#' at position 42: …e() > 1))) #̲set(macro.runtimeOrNonJdkExRegex = ‘(java.lang.RuntimeException|^(?!java.).+)’)
#set($macro.atLeastOneMockedDiThrows = $macro.mockedDIs.containsAnyWith(‘method.throwsException’, true) || $macro.mockedDIs.containsAnyWithNonNull(‘method.returnType.brokenIoInitExpression’) || $macro.mockedDIs.flatMap(‘method.javadocExceptions’).containsAnyWithRegex(‘type.canonicalName’, KaTeX parse error: Expected 'EOF', got '#' at position 36: …kExRegex)) #̲set(macro.atLeastOneMockedDiReturnsFailure = KaTeX parse error: Expected 'EOF', got '#' at position 88: …ression')) #̲set(macro.atLeastOneParamHasIo = $method.parameters.containsAnyWithNonNull(‘type.brokenIoInitExpression’))
## Only render tests for the source method’s declared exceptions if none of the source method’s mocked DIs throw.

If one of the mocked DIs throw, that test case will likely be the case where the source class throws the declared exception(s).

#set( m a c r o . s h o u l d R e n d e r T e s t s F o r D e c l a r e d E x c e p t i o n s = ! macro.shouldRenderTestsForDeclaredExceptions = ! macro.shouldRenderTestsForDeclaredExceptions=!macro.atLeastOneMockedDiThrows && !KaTeX parse error: Expected 'EOF', got '&' at position 28: …tOneParamHasIo &̲& !macro.atLeastOneMockedDiReturnsFailure)
#set($macro.allSourceMethodExceptions = m e t h o d . d e c l a r e d E x c e p t i o n s . u n i o n ( method.declaredExceptions.union( method.declaredExceptions.union(method.javadocExceptions, ‘type.canonicalName’))
#if(!KaTeX parse error: Expected 'EOF', got '#' at position 43: …ments) #̲renderAltFlowTe…method, $macro.allSourceMethodExceptions)
#break
#end

Determine the exception to throw in the broken IO case (if any).

#set($macro.declaredIoException = KaTeX parse error: Expected 'EOF', got '#' at position 90: …n').first) #̲if(!macro.declaredIoException && KaTeX parse error: Expected 'EOF', got '#' at position 48: … == 1) #̲set(macro.declaredIoException = $method.declaredExceptions.first)
#end

Render alternate flow tests based on parameters.

#if(KaTeX parse error: Expected 'EOF', got '#' at position 45: …arams) #̲foreach(param in KaTeX parse error: Expected 'EOF', got '#' at position 32: …s) #̲if(param.type.emptyIoInitExpression)
#renderTestMethod($method, A l t I n f o . f r o m P a r a m W i t h E m p t y I o ( AltInfo.fromParamWithEmptyIo( AltInfo.fromParamWithEmptyIo(param))
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 52: … #̲renderTestMetho…method, A l t I n f o . f r o m P a r a m W i t h B r o k e n I o ( AltInfo.fromParamWithBrokenIo( AltInfo.fromParamWithBrokenIo(param, $macro.declaredIoException))
#end
#end
#end

Render alternate flow tests based on the dependency interactions.

#foreach($di in KaTeX parse error: Expected 'EOF', got '#' at position 26: …edDIs) #̲# Determine inf…macro.isListenableFuture = L i s t e n a b l e F u t u r e N a m e s . c o n t a i n s ( ListenableFutureNames.contains( ListenableFutureNames.contains(di.method.returnType.canonicalName))
#set($macro.isStandardFuture = S t r i n g U t i l s . e q u a l s A n y ( StringUtils.equalsAny( StringUtils.equalsAny(di.method.returnType.canonicalName, ‘java.util.concurrent.Future’, ‘java.util.concurrent.CompletableFuture’, ‘java.util.concurrent.CompletionStage’))
#set($macro.isAnyFuture = KaTeX parse error: Expected 'EOF', got '#' at position 68: …ure')) #̲set(macro.firstTypeParamCanBeEmpty = S t r i n g U t i l s . i s N o t E m p t y ( StringUtils.isNotEmpty( StringUtils.isNotEmpty(di.method.returnType.parameters.first.emptyInitExpression))
#set($macro.firstTypeParamCanBeAbsent = KaTeX parse error: Expected 'EOF', got '&' at position 60: …InitExpression &̲& !StringUtils.equals(KaTeX parse error: Expected 'EOF', got '#' at position 78: …ull')) #̲set(macro.shouldRenderAbsentTest = !KaTeX parse error: Expected 'EOF', got '&' at position 54: …ent.Executor') &̲& (di.method.returnTypeCanBeAbsent || ($macro.isListenableFuture && KaTeX parse error: Expected 'EOF', got '#' at position 44: …ent))) #̲set(macro.shouldRenderEmptyTest = !KaTeX parse error: Expected 'EOF', got '&' at position 54: …ent.Executor') &̲& (di.method.returnType.emptyInitExpression || ($macro.isListenableFuture && KaTeX parse error: Expected 'EOF', got '#' at position 43: …pty))) #̲set(macro.shouldRenderEmptyIoTest = !KaTeX parse error: Expected 'EOF', got '&' at position 54: …ent.Executor') &̲& (di.method.returnType.emptyIoInitExpression || d i . m e t h o d . r e t u r n T y p e . d t o B e a n W i t h I n p u t I o P r o p e r t y ∣ ∣ ( di.method.returnType.dtoBeanWithInputIoProperty || ( di.method.returnType.dtoBeanWithInputIoProperty∣∣(macro.isListenableFuture && KaTeX parse error: Expected 'EOF', got '#' at position 72: …ion))) #̲set(macro.shouldRenderBrokenIoTest = !KaTeX parse error: Expected 'EOF', got '&' at position 54: …ent.Executor') &̲& (di.method.returnType.brokenIoInitExpression || d i . m e t h o d . r e t u r n T y p e . d t o B e a n W i t h I n p u t I o P r o p e r t y ∣ ∣ ( di.method.returnType.dtoBeanWithInputIoProperty || ( di.method.returnType.dtoBeanWithInputIoProperty∣∣(macro.isListenableFuture && KaTeX parse error: Expected 'EOF', got '#' at position 73: …ion))) #̲set(macro.shouldRenderFailureTest = !($di.field.type.isAny(‘java.util.concurrent.Executor’) && KaTeX parse error: Expected 'EOF', got '&' at position 20: …o.isAnyFuture) &̲& (di.method.returnType.failureInitExpression || $macro.isStandardFuture || KaTeX parse error: Expected 'EOF', got '#' at position 36: …ture)) #̲if(!di.method.declaredExceptions.empty)
#set($macro.diExceptionsToUse = KaTeX parse error: Expected 'EOF', got '#' at position 39: …tions) #̲else #set(macro.diExceptionsToUse = $di.method.javadocExceptions.filterItemsWithRegex(‘type.canonicalName’, KaTeX parse error: Expected 'EOF', got '#' at position 40: …egex)) #̲end #set(macro.diExceptionsToUse = m a c r o . d i E x c e p t i o n s T o U s e . u n i o n ( macro.diExceptionsToUse.union( macro.diExceptionsToUse.union(di.method.undeclaredExceptions, ‘type.canonicalName’))
## Render the alt flow tests.
#if(KaTeX parse error: Expected 'EOF', got '#' at position 43: …t) #̲# Render the te…method, A l t I n f o . f r o m D i T o R e t u r n A b s e n t ( AltInfo.fromDiToReturnAbsent( AltInfo.fromDiToReturnAbsent(di))
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 42: …t) #̲# Render the te…method, A l t I n f o . f r o m D i T o R e t u r n E m p t y ( AltInfo.fromDiToReturnEmpty( AltInfo.fromDiToReturnEmpty(di))
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 44: …t) #̲renderTestMetho…method, A l t I n f o . f r o m D i T o R e t u r n E m p t y I o ( AltInfo.fromDiToReturnEmptyIo( AltInfo.fromDiToReturnEmptyIo(di))
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 45: …t) #̲renderTestMetho…method, A l t I n f o . f r o m D i T o R e t u r n B r o k e n I o ( AltInfo.fromDiToReturnBrokenIo( AltInfo.fromDiToReturnBrokenIo(di, KaTeX parse error: Expected 'EOF', got '#' at position 37: …tion)) #̲end #if(macro.shouldRenderFailureTest)
#renderTestMethod($method, A l t I n f o . f r o m D i T o R e t u r n F a i l u r e ( AltInfo.fromDiToReturnFailure( AltInfo.fromDiToReturnFailure(di))
#end
#foreach($exception in KaTeX parse error: Expected 'EOF', got '#' at position 38: …e) #̲if(macro.allSourceMethodExceptions.containsAnyWith(‘type.canonicalName’, $exception.type.canonicalName))
## If the source method throws a checked exception of the same type as the exception thrown by this

dependency interaction, assume it simply lets the exception bubble up; in this case, the test case

should expect the source-method to throw the $exception.

#set($macro.expectedException = KaTeX parse error: Expected 'EOF', got '#' at position 24: …n) #̲else #set(macro.expectedException = KaTeX parse error: Expected 'EOF', got '#' at position 19: …l) #̲end #renderTes…method, A l t I n f o . f r o m D i T h a t T h r o w s ( AltInfo.fromDiThatThrows( AltInfo.fromDiThatThrows(di, $exception, KaTeX parse error: Expected 'EOF', got '#' at position 35: …tion)) #̲end #end #if(macro.shouldRenderTestsForDeclaredExceptions)
#renderAltFlowTestsForDeclaredExceptions($method, $macro.allSourceMethodExceptions)
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderAltFlowTestsForDeclaredExceptions $method, $exceptions)

Renders alt-flow tests where the provided $method is expected to throw the provided $exceptions.

Param: $method - the method for which to render alt-flow tests.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderAltFlowTestsForDeclaredExceptions $method, KaTeX parse error: Expected 'EOF', got '#' at position 17: …xceptions) #̲foreach(declaredException in KaTeX parse error: Expected 'EOF', got '#' at position 21: …tions) #̲renderTestMetho…method, A l t I n f o . f r o m E x p e c t e d E x c e p t i o n ( AltInfo.fromExpectedException( AltInfo.fromExpectedException(declaredException))
#end
#end

##----------------------------------------------------------------------------------------------------------------------

renderTestMethod($method, $altInfo)

Renders the test for the given Method.

Param: $method - the method for which to render the test.

Param: $altInfo - information about which alternate flow this test should cover.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestMethod $method, KaTeX parse error: Expected 'EOF', got '#' at position 14: altInfo) #̲set(_ = KaTeX parse error: Expected 'EOF', got '#' at position 40: …odScope()) #̲if(method.shouldUseSimpleTest)
#renderSimpleTestMethod($method, KaTeX parse error: Expected 'EOF', got '#' at position 32: …Exception) #̲elseif(sourceClass.enum)
#renderTestMethodForEnum($method, KaTeX parse error: Expected 'EOF', got '#' at position 14: altInfo) #̲elseif(sourceClass.packageVisibleStaticCreatorMethods.contains(KaTeX parse error: Expected 'EOF', got '&' at position 9: method) &̲& !sourceClass.singleton && !KaTeX parse error: Expected 'EOF', got '&' at position 27: …ectedException &̲& !altInfo.paramWithEmptyIo && !KaTeX parse error: Expected 'EOF', got '#' at position 36: …kenIo) #̲renderStaticCre…method)
#elseif($springController && c o n t r o l l e r M e t h o d s . c o n t a i n s ( controllerMethods.contains( controllerMethods.contains(method))
#renderTestMethodForController($method, KaTeX parse error: Expected 'EOF', got '#' at position 14: altInfo) #̲elseif(springController && !$method.static) ## Do nothing. This could be a method with @ExceptionHandler, @InitBinder, etc. Those should be covered in the other test cases.
#else

Determine if we should create an assertEquals(…) call.

#set($macro.returnTypeIsArrayWithComparableType = KaTeX parse error: Expected 'EOF', got '&' at position 25: …turnType.array &̲& (method.returnType.deepArrayComponentType.primitive || KaTeX parse error: Expected 'EOF', got '#' at position 68: …uals)) #̲set(macro.shouldCreateAssertEqualsCall =
KaTeX parse error: Expected 'EOF', got '&' at position 19: …hod.returnType &̲& (method.returnType.primitive || $method.returnType.overridesEquals || KaTeX parse error: Expected 'EOF', got '&' at position 27: …rnType.array) &̲& (method.returnType.classT || $method.returnType.allNestedTypeParamsOverrideEquals || KaTeX parse error: Expected 'EOF', got '&' at position 45: …mparableType) &̲& !altInfo.expectedException)
#set($macro.shouldStoreExpectedValue = KaTeX parse error: Expected 'EOF', got '&' at position 36: …sertEqualsCall &̲& !method.returnType.simple)
#set($macro.shouldRenderExceptionHeader = KaTeX parse error: Expected 'EOF', got '&' at position 27: …ectedException &̲& !hasAssertThrows)
## Determine the test case suffix to use for this test method and store the result in: KaTeX parse error: Expected 'EOF', got '#' at position 18: …stCaseSuffix. #̲determineTestCa…method, $altInfo)

@Test #if($macro.shouldRenderExceptionHeader)(expected = ${altInfo.expectedException.type.canonicalNameOrName}.class) #end

public void testKaTeX parse error: Expected '}', got 'EOF' at end of input: …ils.capitalize({method.name})} m e t h o d . o v e r l o a d S u f f i x {method.overloadSuffix} method.overloadSuffix{testCaseSuffix}() throws Exception {
// Setup

Declare parameters to use to invoke the method.

#foreach($param in KaTeX parse error: Expected 'EOF', got '#' at position 71: …)) #̲if(param == KaTeX parse error: Expected 'EOF', got '#' at position 43: … #̲declareAndInitL…param, KaTeX parse error: Expected 'EOF', got '#' at position 53: …e) #̲elseif(param == KaTeX parse error: Expected 'EOF', got '#' at position 44: … #̲declareAndInitL…param, KaTeX parse error: Expected 'EOF', got '#' at position 54: …e) #̲else #declareA…param, true)
#end
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 45: …e) #̲declareAndInitL…method.returnType, true)
#end
#renderStubs($method, $altInfo)

        // Run the test

#set(KaTeX parse error: Expected 'EOF', got '#' at position 20: …o.qualifier = "#̲if(method.static)KaTeX parse error: Expected 'EOF', got '#' at position 34: …icalNameOrName}#̲else{sourceClass.testClassMemberName}#end")
#if(KaTeX parse error: Expected 'EOF', got '#' at position 40: …n) #̲if(hasAssertThrows)
assertThrows(${altInfo.expectedException.type.canonicalNameOrName}.class, () -> KaTeX parse error: Expected 'EOF', got '#' at position 19: …cro.qualifier}.#̲methodCall(method, false));
#renderVerifyStatements($method, $altInfo)
#else
KaTeX parse error: Expected 'EOF', got '#' at position 19: …cro.qualifier}.#̲methodCall(method, false);
#end
#else
#if($method.returnType) final $method.returnType.canonicalText result = #end KaTeX parse error: Expected 'EOF', got '#' at position 19: …cro.qualifier}.#̲methodCall(method, false);

            // Verify the results

#if(KaTeX parse error: Expected 'EOF', got '#' at position 53: … #̲set(macro.expectedValueExpression = "#if( m a c r o . s h o u l d S t o r e E x p e c t e d V a l u e ) macro.shouldStoreExpectedValue) macro.shouldStoreExpectedValue)method.returnType.testClassLocalFieldName #else KaTeX parse error: Expected 'EOF', got '#' at position 34: …initExpression #̲end") …macro.expectedValueExpression, ‘result’, KaTeX parse error: Expected 'EOF', got '#' at position 33: …); #̲end #renderVer…method, KaTeX parse error: Expected 'EOF', got '#' at position 18: …tInfo) #̲end } #end…_ = $CodeStyleUtils.endMethodScope())
#end

##----------------------------------------------------------------------------------------------------------------------

renderTestMethodForController $method, $altInfo)

Renders the test for the given controller Method.

Param: $method - the method for which to render the test.

Param: $altInfo - information about which alternate flow this test should cover.

##----------------------------------------------------------------------------------------------------------------------
#macro(renderTestMethodForController $method, $altInfo)
## Determine the test case suffix to use for this test method and store the result in: KaTeX parse error: Expected 'EOF', got '#' at position 18: …stCaseSuffix. #̲determineTestCa…method, KaTeX parse error: Expected 'EOF', got '#' at position 14: altInfo) #̲# Determine the…macro.pathHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determinePath(method, KaTeX parse error: Expected 'EOF', got '#' at position 23: …athHolder) #̲# Determine the…macro.pathArgsHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determinePathAr…method, KaTeX parse error: Expected 'EOF', got '#' at position 27: …rgsHolder) #̲# Determine if …macro.multipartUploadHolder = KaTeX parse error: Expected 'EOF', got '#' at position 35: …te(false)) #̲determineIfMult…method, KaTeX parse error: Expected 'EOF', got '#' at position 34: …oadHolder) #̲# Determine the…macro.requestMethodHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determineReques…method, $macro.multipartUploadHolder.value, KaTeX parse error: Expected 'EOF', got '#' at position 32: …hodHolder) #̲# Determine the…macro.responseContentTypeHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determineRespon…method, KaTeX parse error: Expected 'EOF', got '#' at position 38: …ypeHolder) #̲# Determine the…macro.expectedResponseCodeHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determineExpect…altInfo.expectedException, KaTeX parse error: Expected 'EOF', got '#' at position 39: …odeHolder) #̲# Determine the…macro.httpParamsCallStringHolder = KaTeX parse error: Expected 'EOF', got '#' at position 29: ….create()) #̲determineHttpPa…method, $macro.requestMethodHolder.value, $macro.multipartUploadHolder.value, KaTeX parse error: Expected 'EOF', got '#' at position 39: …ingHolder) #̲if(macro.requestMethodHolder.value == ‘trace’)
#set($macro.requestMethodCall = 'request(HttpMethod.TRACE, ’ + ‘"’ + $macro.pathHolder.value + ‘"’ + KaTeX parse error: Expected 'EOF', got '#' at position 39: …lue + ')') #̲else #set(macro.requestMethodCall = $macro.requestMethodHolder.value + ‘(’ + ‘"’ + $macro.pathHolder.value + ‘"’ + KaTeX parse error: Expected 'EOF', got '#' at position 39: …lue + ')') #̲end @Test publi…{StringUtils.capitalize(KaTeX parse error: Expected 'EOF', got '}' at position 15: {method.name})}̲{method.overloadSuffix}KaTeX parse error: Expected '}', got '#' at position 49: …on { // Setup #̲renderStubs(method, $altInfo)

// Run the test
final MockHttpServletResponse response = m o c k M v c M e m b e r N a m e . p e r f o r m ( {mockMvcMemberName}.perform( mockMvcMemberName.perform({macro.requestMethodCall} N e w l i n e {Newline} Newline{macro.httpParamsCallStringHolder}.accept( m a c r o . r e s p o n s e C o n t e n t T y p e H o l d e r ) ) macro.responseContentTypeHolder)) macro.responseContentTypeHolder)){Newline}.andReturn().getResponse();

    // Verify the results

#assertEqualsCall(KaTeX parse error: Expected 'EOF', got '#' at position 77: …', false); #̲assertEqualsCal…method, $altInfo)
}
#end

##----------------------------------------------------------------------------------------------------------------------

determineExpectedResponseCode($expectedException, $expectedResponseCodeHolder)

Determines the expected response code based on the provided exception and writes the string to

$expectedResponseCodeHolder.value.

Param: $expectedException - the expected exception for the test case.

Param: $expectedResponseCodeHolder - the MutableString that will contain the expected response code.

##----------------------------------------------------------------------------------------------------------------------
#macro(determineExpectedResponseCode $expectedException, KaTeX parse error: Expected 'EOF', got '#' at position 33: …odeHolder) #̲if(expectedException)
#set(KaTeX parse error: Expected 'EOF', got '#' at position 84: ….value()') #̲else #set(expectedResponseCodeHolder.value = ‘HttpStatus.OK.value()’)
#end
#end

##----------------------------------------------------------------------------------------------------------------------

determineResponseContentType($method, $responseContentTypeHolder)

Determines the content type to use for the response and stores the result in $responseContentTypeHolder.value.

Param: $method - the expected exception for the test case.

Param: $responseContentTypeHolder - the MutableString that will contain the expected response code.

##----------------------------------------------------------------------------------------------------------------------
#macro(determineResponseContentType $method, KaTeX parse error: Expected 'EOF', got '#' at position 32: …ypeHolder) #̲set(macro.superMethods = F l u e n t L i s t . o f ( FluentList.of( FluentList.of(method).concat(KaTeX parse error: Expected 'EOF', got '#' at position 27: …rMethods)) #̲if(restController || $macro.superMethods.containsAnyWithAnnotation(‘ResponseBody’, ‘JsonView’)
|| $method.returnType.isAny(‘org.springframework.http.HttpEntity’) || KaTeX parse error: Expected 'EOF', got '#' at position 90: …ity')) #̲set(responseContentTypeHolder.value = ‘MediaType.APPLICATION_JSON’)
#else
#set($responseContentTypeHolder.value = ‘MediaType.TEXT_HTML’)
#end
#end

##----------------------------------------------------------------------------------------------------------------------

determineIfMultipartUpload($method, $multipartUploadHolder)

Determines if the controller method is handling a multipart upload request and saves the output (boolean) to

$multipartUploadHolder.value.

Param: $method - the method.

Param: $multipartUploadHolder - the MutableBoolean that will contain the output value.

##----------------------------------------------------------------------------------------------------------------------
#macro(determineIfMultipartUpload $method, KaTeX parse error: Expected 'EOF', got '#' at position 28: …oadHolder) #̲set(multipartUploadHolder.value = false)
#set($macro.superMethods = F l u e n t L i s t . o f ( FluentList.of( FluentList.of(method).concat(KaTeX parse error: Expected 'EOF', got '#' at position 27: …rMethods)) #̲set(macro.superParams = m e t h o d . p a r a m e t e r s . c o n c a t ( method.parameters.concat( method.parameters.concat(method.superMethods.flatMap(‘parameters’)))
## Check the controller method(s) mapping annotations to see if one of them has consumes=multipart.
#if($macro.superMethods.flatMap(‘annotations’).filterItemsWithAny(‘name’, C o n t r o l l e r M e t h o d A n n o t a t i o n s ) . f l a t M a p ( ′ p a r a m e t e r s ′ ) . f i l t e r ( ′ k e y ′ , ′ c o n s u m e s ′ ) . c o n t a i n s A n y W i t h R e g e x ( ′ v a l u e . t e x t ′ , ′ . ∗ ( M U L T I P A R T ∣ m u l t i p a r t / ) . ∗ ControllerMethodAnnotations).flatMap('parameters').filter('key', 'consumes').containsAnyWithRegex('value.text', '^.*(MULTIPART_|multipart/).* ControllerMethodAnnotations).flatMap(parameters).filter(key,consumes).containsAnyWithRegex(value.text,′.(MULTIPARTmultipart/).'))
#set(KaTeX parse error: Expected 'EOF', got '#' at position 45: … true) #̲break(macro)
#end
#if(KaTeX parse error: Expected 'EOF', got '#' at position 69: …art')) #̲set(multipartUploadHolder.value = true)
#break(KaTeX parse error: Expected 'EOF', got '#' at position 12: macro) #̲end #foreach(param in KaTeX parse error: Expected 'EOF', got '#' at position 28: …eters) #̲if(param.type.isOrHasAnyNestedTypeParamWith(KaTeX parse error: Expected 'EOF', got '#' at position 39: …)) #̲set(multipartUploadHolder.value = true)
#break(KaTeX parse error: Expected 'EOF', got '#' at position 16: macro) #̲end #determine…param, KaTeX parse error: Expected 'EOF', got '#' at position 32: …older) #̲if(multipartUploadHolder.value)
#break($macro)
#end
#end
#end

##----------------------------------------------------------------------------------------------------------------------

determineIfClassHasMultipartFile($method, $paramClassHasMultipartHolder)

Determines if the parameter or the parameter’s inner most type parameter have a member field containing a multipart

file type. This macro writes the output boolean to $paramClassHasMultipartHolder.value.

Param: $param - the parameter

Param: $paramClassHasMultipartHolder - the MutableBoolean that will contain the output.

##----------------------------------------------------------------------------------------------------------------------
#macro(determineIfClassHasMultipartFile $param, KaTeX parse error: Expected 'EOF', got '#' at position 35: …artHolder) #̲set(paramClassHasMultipartHolder.value = false)
#set($macro.typeToUse = KaTeX parse error: Expected 'EOF', got '#' at position 17: …aram.type) #̲set(macro.hasMultipleTypeParams = false)
#foreach(KaTeX parse error: Expected 'EOF', got '#' at position 23: …..25]) #̲if(macro.typeToUse.parameters.empty)
#break(KaTeX parse error: Expected 'EOF', got '#' at position 18: …reach) #̲elseif(macro.typeToUse.parameters.size() > 1)
#set(KaTeX parse error: Expected 'EOF', got '#' at position 49: …e) #̲break(foreach)
#else
#set($macro.typeToUse = KaTeX parse error: Expected 'EOF', got '#' at position 43: …first) #̲end #end #if(macro.hasMultipleTypeParams)
#break(KaTeX parse error: Expected 'EOF', got '#' at position 12: macro) #̲end #set(macro.paramClass = C l a s s U t i l s . r e s o l v e C l a s s ( ClassUtils.resolveClass( ClassUtils.resolveClass(macro.typeToUse))
#if(KaTeX parse error: Expected 'EOF', got '#' at position 27: …Class) #̲foreach(field in KaTeX parse error: Expected 'EOF', got '#' at position 38: …s) #̲if(field.type.isOrHasAnyNestedTypeParamWith(KaTeX parse error: Expected 'EOF', got '#' at position 43: … #̲set(paramClassHasMultipartHolder.value = true)
#break($macro)
#end
#end
#end
#end

##----------------------------------------------------------------------------------------------------------------------

determinePath($method, $pathHolder)

Determines the path to use for the controller method and writes it to $pathHolder.value.

Param: $method - the method to determine the controller path for.

Param: $pathHolder - the MutableString the controller path will be written to.

##----------------------------------------------------------------------------------------------------------------------
#macro(determinePath $method, KaTeX parse error: Expected 'EOF', got '#' at position 17: …athHolder) #̲set(pathHolder.value = ‘path’)
#set($macro.superMethods = F l u e n t L i s t . o f ( FluentList.of( FluentList.of(method).concat(KaTeX parse error: Expected 'EOF', got '#' at position 27: …rMethods)) #̲set(macro.annotationPath = $macro.superMethods.flatMap(‘annotations’).filterItemsWithAny(‘name’, $RequestMappingAnnotations).flatMap(‘parameters’).filter(‘key’, ‘path’, ‘value’).filterOut(‘value.text’, ‘{}’).first.value.text)
## Replace environment variable placeholders like KaTeX parse error: Expected 'EOF', got '#' at position 48: …companyName/. #̲set(macro.tempPath = S t r i n g U t i l s . r e p l a c e A l l ( StringUtils.replaceAll( StringUtils.replaceAll(macro.annotationPath, ‘${(.*?)}’, '/KaTeX parse error: Expected 'EOF', got '#' at position 11: 1/')) #̲# The path can …macro.tempPath = S t r i n g U t i l s . l o n g e s t ( StringUtils.longest( StringUtils.longest(StringUtils.substringsBetween(KaTeX parse error: Expected 'EOF', got '#' at position 28: …th, '"'))) #̲if(macro.tempPath)
#set($pathHolder.value = $basePath + ‘/’ + KaTeX parse error: Expected 'EOF', got '#' at position 21: ….tempPath) #̲elseif(macro.annotationPath)
## The path could be a reference to a constant; e.g. MyPaths.FooPath.
#set($pathHolder.value = $basePath + ‘/’ + ‘path’)
#else

There is no mapping annotation with a path parameter. Use the base path.

#set($pathHolder.value = $basePath)
#end

Remove duplicate forward slashes.

#set($pathHolder.value = $pathHolder.value.replaceAll(‘/+’, ‘/’).trim())
#end

##----------------------------------------------------------------------------------------------------------------------

determinePathArgs($method, $pathArgsHolder)

Determines the path variables to use for the controller method and writes it to determinePathArgs.value.

Param: $method - the method to determine the controller path args for.

Param: $pathArgsHolder - the MutableString the controller path args String will be written to.

##----------------------------------------------------------------------------------------------------------------------
#macro(determinePathArgs $method, KaTeX parse error: Expected 'EOF', got '#' at position 21: …rgsHolder) #̲set(pathArgsHolder.value = ‘’)
#foreach($param in KaTeX parse error: Expected 'EOF', got '#' at position 28: …eters) #̲set(macro.superParamsAtIndex = F l u e n t L i s t . o f ( FluentList.of( FluentList.of(param).concat( m e t h o d . g e t S u p e r M e t h o d P a r a m e t e r s A t I n d e x ( method.getSuperMethodParametersAtIndex( method.getSuperMethodParametersAtIndex(foreach.index)))
#if(KaTeX parse error: Expected 'EOF', got '#' at position 99: …)) #̲# Determine the…macro.paramValue = ‘"’ + KaTeX parse error: Expected 'EOF', got '#' at position 39: …') #̲if(param.type.isOrHasAnyNestedTypeParamWith(KaTeX parse error: Expected 'EOF', got '#' at position 32: … #̲set(macro.paramValue = ‘false’)
#elseif( p a r a m . t y p e . i s O r H a s A n y N e s t e d T y p e P a r a m W i t h ( param.type.isOrHasAnyNestedTypeParamWith( param.type.isOrHasAnyNestedTypeParamWith(NumericTypes))
#set(KaTeX parse error: Expected 'EOF', got '#' at position 37: …') #̲end #set(pathArgsHolder.value = $pathArgsHolder.value + ', ’ + $macro.paramValue)
#end
#end
#end

##----------------------------------------------------------------------------------------------------------------------

determineHttpParamsCallString($method, $requestMethod, $multipartUpload, $httpParamsCallStringHolder)

Determines the string of method calls needed to add parts to the HTTP request that the controller method is expecting.

The result is stored as a String in $httpParamsCallStringHolder.value.

Param: $method - the controller method to create the http method calls for.

Param: $requestMethod - the request method determined for this method; e.g. ‘get’, ‘post’, ‘multipart’, etc.

Param: $multipartUpload - boolean indicating whether or not this is a multipart request.

Param: $httpParamsCallStringHolder - MutableString object whose value will contain the output of this macro.

##----------------------------------------------------------------------------------------------------------------------
#macro(determineHttpParamsCallString $method, $requestMethod, $multipartUpload, KaTeX parse error: Expected 'EOF', got '#' at position 33: …ingHolder) #̲set(httpParamsCallStringHolder.value = ‘’)
#set($macro.fileParamsCallStringHolder = KaTeX parse error: Expected 'EOF', got '#' at position 31: …reate('')) #̲set(macro.superParams = m e t h o d . p a r a m e t e r s . c o n c a t ( method.parameters.concat( method.parameters.concat(method.superMethods.flatMap(‘parameters’)))
#set($macro.superMethods = F l u e n t L i s t . o f ( FluentList.of( FluentLis

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java POI(Poor Obfuscation Implementation)是一个用于操作Microsoft Office文件格式的Java库。它支持从Excel文件中读取和写入数据,以及创建和修改Word和PowerPoint文档。 在Java POI中,我们可以使用实体类来填充Excel模板实体类是一个Java类,其中包含了与Excel模板中每个单元格对应的属性。在填充过程中,我们可以通过对实体类属性进行赋值,将数据填充到Excel模板中。 以下是一个示例实体类的代码: ``` public class Student { private String name; private int age; private String gender; private double score; // getters and setters // ... // constructor public Student(String name, int age, String gender, double score) { this.name = name; this.age = age; this.gender = gender; this.score = score; } } ``` 在Excel模板中,我们可以使用占位符来标记需要填充数据的单元格。例如,我们可以在单元格中输入“{{name}}”来表示该单元格需要填充学生姓名。 接下来,我们可以使用Java POI来加载Excel模板文件,并使用实体类来填充数据。以下是一个示例代码: ``` public class ExcelFiller { public static void main(String[] args) throws IOException, InvalidFormatException { // 加载Excel模板 Workbook workbook = WorkbookFactory.create(new File("template.xlsx")); Sheet sheet = workbook.getSheetAt(0); // 填充数据 Student student = new Student("Tom", 18, "Male", 90.5); Row row = sheet.getRow(1); Cell cell = row.getCell(0); cell.setCellValue(student.getName()); row.getCell(1).setCellValue(student.getAge()); row.getCell(2).setCellValue(student.getGender()); row.getCell(3).setCellValue(student.getScore()); // 保存文件 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); outputStream.close(); workbook.close(); } } ``` 在上面的代码中,我们首先通过WorkbookFactory类加载Excel模板文件。然后,我们获取第一个Sheet,并使用实体类填充第二行的数据。最后,我们将修改后的Workbook保存为一个新的Excel文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值