在Spring Boot应用程序中,使用MockMvc进行单元测试是一种有效的方式,可以验证控制器的行为和API的正确性。在这篇博客中,我们将介绍如何使用MockMvc对用户控制器(UserController)进行测试,该控制器涉及用户信息的增删改查操作。
UserController测试类
package com.lfsun.mockmvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lfsun.mockmvc.entity.User;
import com.lfsun.mockmvc.service.UserService;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays;
import java.util.List;
import static o