网上基本都是参考官方的使用方式,使用了import static,个人感觉这种方式特别不好,代码提示性不友好。所以在此进行说明,也方便自己以后使用。
1. 引入spring-test相关jar包,springboot只需引入spring-boot-starter-test即可
1 2 3 4 5 |
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> |
2. 写好controller,开始写test类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import org.front.server.application; import org.front.server.web.control.testcontroller; import org.hamcrest.matchers; import org.junit.before; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.springapplicationconfiguration; import org.springframework.http.mediatype; import org.springframework.test.context.junit4.springjunit4classrunner; import org.springframework.test.context.web.webappconfiguration; import org.springframework.test.web.servlet.mockmvc; import org.springframework.test.web.servlet.request.mockmvcrequestbuilders; import org.springframework.test.web.servlet.result.mockmvcresulthandlers; import org.springframework.test.web.servlet.result.mockmvcresultmatchers; import org.springframework.test.web.servlet.setup.mockmvcbuilders; import org.springframework.web.context.webapplicationcontext; //网上很多会在这里使用import static,主要导入的是mockmvcrequestbuilders,mockmvcresultmatchers,matchers这三个类中的方法。 /** * @author zz * @date 2017年7月4日 * */ @runwith (springjunit4classrunner. class ) //@springapplicationconfiguration(classes = mockservletcontext.class)//这个测试单个controller,不建议使用 @springapplicationconfiguration (classes = application. class ) //这里的application是springboot的启动类名。 @webappconfiguration public class applicationtests { @autowired private webapplicationcontext context; private mockmvc mvc;
@before public void setup() throws exception { // mvc = mockmvcbuilders.standalonesetup(new testcontroller()).build(); mvc = mockmvcbuilders.webappcontextsetup(context).build(); //建议使用这种 } @test public void test1() throws exception { mvc.perform(mockmvcrequestbuilders.get( "/data/getmarkers" ) .contenttype(mediatype.application_json_utf8) .param( "lat" , "123.123" ).param( "lon" , "456.456" ) .accept(mediatype.application_json)) .andexpect(mockmvcresultmatchers.status().isok()) .anddo(mockmvcresulthandlers.print()) .andexpect(mockmvcresultmatchers.content().string(matchers.containsstring( "success" )));
} } |
相信这样,基本开发过javaweb的就都能看懂了。通过方法的字面意思应该都能看懂方法含义,如果实在不懂请看源码或者官方api。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://HdhCmsTestcnblogs测试数据/qlong8807/p/7121522.html
查看更多关于spring-mvc/springboot使用MockMvc对controller进行测试的详细内容...