用groovy编写springboot单元测试
2018-12-13 本文已影响0人
阿东7
用groovy编写springboot单元测试,且java和groovy混合编程
源代码下载地址
https://github.com/wengmingdong/springboot-groovy-mixed
1. 在pom.xml添加maven的groovy插件编译器 (在我的idea环境中springboot都不需要添加这插件都可以跑groovy)
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version><!-- 3.1 is the minimum -->
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<compilerArguments>
<indy/>
<configScript>config.groovy</configScript>
</compilerArguments>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.9.2-01</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>2.4.3-01</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2. 编写带body内容的controller
@RestController
@RequestMapping("/sgmixed/rest/test")
public class MixedController {
@RequestMapping(
value = "/hello",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public String hello(@RequestBody HelloDataBean helloDataBean) {
System.out.println(JackJsonUtils.toStr(helloDataBean));
return "hello world";
}
}
3. 编写groovy测试类
class MxiedGroovyTest extends BaseTest {
@Test
void helloworldMixed() throws Exception {
def body = '''
{
"springboot":"hi springboot",
"groovy":"hi groovy",
"hello":"hi hello",
"world":"hi world"
}
''';
def responseString = mockMvc.perform(
post("/sgmixed/rest/test/hello")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(body)
).andExpect(status().isOk())
.andDo(print())
.andReturn().getResponse().getContentAsString();
println(responseString);
}
}