Springboot + Mockito

参考:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/MockMvc.html


package com.xfhl.meeting;

import com.xfhl.meeting.controller.mobile.AppController;
import com.xfhl.meeting.entity.App;
import com.xfhl.meeting.service.IAppService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.time.LocalDateTime;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(MockitoJUnitRunner.class)
public class M1 {

    private MockMvc mockMvc;
    @InjectMocks
    private AppController appController;
    @Mock
    private IAppService iAppService;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(appController).build();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void home() throws Exception {

        App app = new App();
        app.setId(1);
        app.setAddTime(LocalDateTime.now());
        app.setDescription("xxx");

        Mockito.when(iAppService.getLastOne(Mockito.anyString())).thenReturn(app);

        this.mockMvc.perform(MockMvcRequestBuilders.get("/meeting/mobile/app/checkUpdate/1"))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn();
    }
}


-----------------POST--------------
Mockito.doNothing().when(iUserService).sendMobileCode(Mockito.anyString());
        Mockito.when(iUserService.list(Mockito.any())).thenReturn(Lists.newArrayList());

        CodeDTO codeDTO = new CodeDTO();
        codeDTO.setAction("register");
        codeDTO.setMobile("12345678");

        String mvcResult= mockMvc.perform(MockMvcRequestBuilders.post("/meeting/mobile/auth/code").contentType(MediaType.APPLICATION_JSON)
        .content(JSON.toJSONString(codeDTO)).characterEncoding("UTF-8"))
                .andDo(print())
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(mvcResult);

 

你可能感兴趣的:(随手记)