Junit

https://www.cnblogs.com/qinxu/p/7844964.html

https://blog.csdn.net/lvyuan1234/article/details/82836052

 

 

 

根据条件来生成代码

https://stackoverflow.com/questions/47202115/intellij-idea-junit-test-class-template-depending-on-condition

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.

 

 

问:

@AutoConfigureMockMvc @SpringBootTest是否等同于
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
 
答:
不一样,@SpringBootTest的webEnvironment属性Mock (默认值)是加载WebApplicationContext并提供Mock Servlet环境。而@AutoConfiureMockMvc是自动配置MockMvc
 
 
######################################################################################## 
## 模板作者: 陆慧
## Velocity 模板语言参考:https://www.cnblogs.com/xiohao/p/5788932.html
## 可用变量:
## $ entryList.methodList-方法组合列表
## $ entryList.privateMethodList-私有方法组合的列表
## $ entryList.fieldList-类作用域字段名称的ArrayList
## $ entryList.className-类名
## $ entryList.packageName-软件包名称
## $ today  -  MM/dd/yyyy格式的今天日期
##
## MethodComposite变量:
## $ method.name-方法名称
## $ method.signature-字符串形式的完整方法签名
## $ method.reflectionCode-表示注释掉的反射代码的字符串列表,以访问方法(私有方法)
## $ method.paramNames-表示方法参数名称的字符串列表
## $ method.paramClasses-表示方法参数类的字符串列表
##
## 您可以使用下面的“ testClass”变量配置输出类名称。
## 这里有些例子:
## Test $ {entry.ClassName}-将产生TestSomeClass
## $ {entry.className} Test-将产生SomeClassTest
## 
######################################################################################## 
## 
#macro (cap $strIn)$strIn.valueOf($strIn.charAt(0)).toUpperCase()$strIn.substring(1)#end 
## Iterate through the list and generate testcase for every entry. 
#foreach ($entry in $entryList) 
#set( $testClass="${entry.className}Test")
##
#if($testClass.contains("Controller")) 
## 定义一个这个类的实例变量,都用小写 
#set( $ClassName="${entry.className}")  
#set( $lowercaseClassName=$ClassName.toLowerCase())  
#end 
## 
package $entry.packageName; 
import com.svw.ematrix.MasterDataApplication;
import org.junit.Test; 
import org.junit.Before; 
import org.junit.After; 
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.Assert;
import org.springframework.http.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.annotation.Rollback;
import com.alibaba.fastjson.JSON;
import org.hamcrest.core.Is;
#if($testClass.contains("Controller"))
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
#end
/** 
* ${entry.className} Tester. 
* 
* @author  ETP-1 LuHui
* @since <pre>$today</pre> 
* @version 1.0 
*/ 

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback
#if($testClass.contains("Controller"))
@AutoConfigureMockMvc
#end
public class $testClass { 
#if($testClass.contains("Controller")) 
    @Autowired
    protected MockMvc mockMvc;
    
    @Autowired
    private $ClassName $lowercaseClassName;
#end

    @Before
    public void before() throws Exception { 
       this.mockMvc = MockMvcBuilders.standaloneSetup(this.$lowercaseClassName).build();
    } 

    @After
    public void after() throws Exception { 
    } 

#foreach($method in $entry.methodList) 
    /** 
    * 
    * Method: $method.signature 
    * 
    */ 
    @Test
    public void test#cap(${method.name})() throws Exception { 
        String requestUrl="";//TODO: you must define the api  like '/masterdata/users'
#set( $methodname="${method.name}")
#if($methodname.contains("insert") || $methodname.contains("update")|| $methodname.contains("delete") )
        Object XXXXX=new Object();//TODO: you must define a instance of a real Class.
#end        
        RequestBuilder requestBuilder
            = MockMvcRequestBuilders
            .post(requestUrl)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
#if($methodname.contains("insert") || $methodname.contains("update") || $methodname.contains("delete"))
            .accept(MediaType.APPLICATION_JSON_UTF8)
            .content(JSON.toJSONBytes(XXXXX));  //TODO:  [insert] / [update] / [delete] need it.  [select] needn't.
#else
            .accept(MediaType.APPLICATION_JSON_UTF8);
#end
        ResultActions resultActions = this.mockMvc.perform(requestBuilder);
        resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();
        Assert.assertThat(resultActions.andReturn().getResponse().getStatus(), Is.is(200)); 
    } 

#end 

#foreach($method in $entry.privateMethodList) 
    /** 
    * 
    * Method: $method.signature 
    * 
    */ 
    @Test
    public void test#cap(${method.name})() throws Exception { 
        //TODO: Test goes here... 
#foreach($string in $method.reflectionCode) 
        $string 
#end 
        } 

#end 
} 
#end

 

 

posted @ 2019-10-10 13:19  Daniel_Lu  阅读(420)  评论(0编辑  收藏  举报