如何编写适当的JUnit测试用例剩余控制器

时间:2019-12-16 11:44:30

标签: junit mockito

我想使用Mockito框架编写JUnit测试用例的休息控制器。我想知道如何为get和post之类的http请求编写测试用例。还有如何测试上传文档的api。

1 个答案:

答案 0 :(得分:0)

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class ControllerTest {
    @Autowired
    private MockMvc mvc;

    @Mock
    Service service;

    @InjectMocks
    private Controller controller;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.standaloneSetup(marketplaceCatalogController)
               .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
               .setViewResolvers(new ViewResolver() {
                   @Override
                   public View resolveViewName(String viewName, Locale locale) throws Exception {
                      return new MappingJackson2JsonView();
                  }
               }).build();
    }

    @Test
    public void testGetMethod() throws Exception {        
        when(service.getMethod(Mockito.any(SomeClass.class))).thenReturn(new SomeOtherClass);   
        doNothing().when(service).someMethod();     
        mvc.perform(get("/get-method").param("paramKey", 
                                "paramValue")).andExpect(status().isOk()).andDo(print());
    }

    @Test
    public void testStatusTnC() throws Exception {
        String payload = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
        mvc.perform(post("/post-method").content(payload)).andExpect(status().isOk()).andDo(print());
    }

    @Test
    public void testUploadFile() throws Exception {
        when(service.uploadSomeContent(any(), any(), anyString(), anyString())).thenReturn(new SomeClass());        
        mvc.perform(fileUpload("/post-request/uploadFile").file("somefile", "Hello, World!".getBytes()).param("param1", "value1").contentType(MediaType.MULTIPART_FORM_DATA)).andExpect(status().isOk()).andDo(print());
    }
}