测试Service方法

public int getMenAge(Integer id) {
        Men m = mp.findOne(id);
        return m.getAge();
    }

在test目录下建立test类:

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.jimo.service.MenService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Autowired
    private MenService ms;

    @Test
    public void menServiceTest() {
        Assert.assertEquals(1, ms.getMenAge(1));
    }
}

结果:

java.lang.AssertionError: expected:<1> but was:<7>

测试Controller的方法

需要类似在postman里传入url来测试

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired
    MockMvc mvc;

    @Test
    public void testGetAll() {
        try {
            mvc.perform(MockMvcRequestBuilders.get("/men/getAll"))
            .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.content().string("xxx"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试结果:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /men/getAll
       Parameters = {}
          Headers = {}

Handler:
             Type = com.jimo.controller.MenController
           Method = public java.util.List<com.jimo.model.Men> com.jimo.controller.MenController.getAllMen()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {X-Application-Context=[application:-1], Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = [{"id":1,"name":"lonely","age":7},{"id":3,"name":"lily","age":14},
             {"id":4,"name":"lily12","age":20}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

mvn clean package

也可以在打包时自动测试,但是如果想跳过,可以这样写:

mvn clean package -Dmaven.test.skip=true

results matching ""

    No results matching ""