JUnit测试SpringMVC

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38095094/article/details/78076537

JUnit测试

@Test

说明:被这个注解标记的类被认为是测试类,在@Test中可以加上一些说明

name function
@expected 期望测试类返回怎样的结果或者抛出怎样的异常
@timeout 期望这个测试类运行的最长时间
@Test(expected = java.io.IOException,timeout=2000)
public void MethodTest(){}  

//期望测试程序抛出IO异常,并且运行时间最长为2秒,否则测试失败  

@RunWith 和 @SuitClasses

说明:这两个注解同时使用可以一次同时运行多个测试类

    package com.test.junit;  

import org.junit.Test;  

public class TestSuit001 {  

    @Test  
    public void test()  
    {  
        System.out.println("test001");  
    }  
}  
    package com.test.junit;  

import org.junit.Test;  

public class TestSuit002 {  

    @Test  
    public void test()  
    {  
        System.out.println("test002");  
    }  
}
    package com.test.junit;  

import org.junit.runner.RunWith;  
import org.junit.runners.Suite;  


@RunWith(Suite.class)  
@Suite.SuiteClasses({TestSuit001.class, TestSuit002.class})  
public class TestSuit {  

} 

运行TestSuit,便可以同时运行上面两个测试类。

@Before 和 @After

说明:测试方法运行之前都会先运行@Before标记的测试方法,测试运行之后都会运行@After标记的测试方法

@BeforeClass 和 @AfterClass

说明:测试类运行之前都会先运行@BeforeClas标记的测试方法,测试运行之后都会运行@After标记的测试方法,注意这里是类运行之前

测试SpringMVC的controller

  • @RunWith(SpringJUnit4ClassRunner.class): 表示使用Spring Test组件进行单元测试,这是集合了JUnit和SpringTest的测试框架
  • @ContextHierarchy({
    @ContextConfiguration(locations = “classpath:spring.xml”),
    @ContextConfiguration(locations = “classpath:springmvc.xml”)
    })
  • ContextConfiguration 定Bean的配置文件信息;如果需要多个配置文件信息,则使用@ContextHierarchy内部包含多个配置文件的信息
  • transactionConfiguration(transactionManager=”transactionManager”,defaultRollback=true)配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用
  • WebAppConfiguration: 使用这个Annotate会在跑单元测试的时候真实的启动一个web服务,然后开始调用Controller的Rest API,待单元测试跑完之后再将web服务停掉;

说明:在spring开发中,可以使用spring自带的M ckMvc这个类进行Mock测试

import controller.UserController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

    @RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
        @ContextConfiguration(locations = "classpath:spring.xml"),
        @ContextConfiguration(locations = "classpath:springmvc.xml")
})

@TransactionConfiguration(transactionManager = "transactionManager" ,defaultRollback = true)
@Transactional

@WebAppConfiguration
public class UserControllerTest {
    private Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp(){
        //初始化MockMvc对象
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

@Test
    public void TestMethodLogin() throws Exception {
        String responseString = mockMvc.perform(
                get("/download/detail")
        .contentType(MediaType.APPLICATION_JSON).param("userId", String.valueOf(9))).andExpect(status().isOk()).andDo(
                print()).andReturn().getResponse().getContentAsString();
    System.out.println("---------返回的json"+responseString);


    //perform中的get说明请求是以get方式,
    //contentType是请求参数的类型
    //param是请求的参数,第一个参数是请求参数的名称,第二个是值  
    //andExpect(Status().isOK())表示期待的返回值的OK(200)  
    //andDo表示请求之后需要做的事情,这里是得到返回的内容
}

}

猜你喜欢

转载自blog.csdn.net/qq_38095094/article/details/78076537