https://www.cnblogs.com/qinxu/p/7844964.html
根据条件来生成代码
The JUnit code generation templates can be found under Settings > File And Code templates > Code.
You can‘t really create separate code templates, but what you could do is add logic to the existing templates. They use Velocity based directives. So if, for example, we take the existing JUnit 4 template:
import static org.junit.Assert.*;
#parse("File Header.java")
public class ${NAME} {
${BODY}
}
We can modify it to the following:
import static org.junit.Assert.*;
#if($CLASS_NAME.contains("Service"))
//Import whatever you need for services here.
#end
#if($CLASS_NAME.contains("Controller"))
//Import whatever you need for controllers here.
#end
#parse("File Header.java")
#if($CLASS_NAME.contains("Controller"))
#set($CLASS_SUFFIX = ".class" )
@RunWith(SpringRunner.class)
@RunWithMock
@WebMvcTest(controllers = $CLASS_NAME$CLASS_SUFFIX)
#end
#if($CLASS_NAME.contains("Service"))
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE)
#end
public class ${NAME} {
${BODY}
}
This way if you generate a new JUnit 4 test class through the context menu (hit alt-enter on the class name of the class you want to test and generate new test) it will generate different output if the name of the class to test contains ‘Controller‘ or ‘Service‘. You might want to change that to endswith instead of contains depending on whatever naming conventions you use. I‘ve left out the actual import statements in both cases, but I‘m sure you‘ll be able to add those.
原文:https://www.cnblogs.com/lhuser/p/11578276.html