如何为OneToMany连接编写单元测试(测试Rest端点)?

时间:2019-02-05 16:42:59

标签: java spring unit-testing mocking mockito

我是编程的初学者,所以如果我问一个琐碎的问题,请原谅我。

我的问题是,如何使我的测试方法能够检查与CalendarModel相关的UserModel的OneToMany连接。我想检查一下,列表中是否包含正确的实体,因此对UserModel的所有4个字段进行了测试。

我的用户模型:

    import com.fasterxml.jackson.annotation.JsonIgnore;

    import java.util.List;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;

@Entity
public class UserModel {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @OneToMany(mappedBy = "id")
  @JsonIgnore
  private List<CalendarModel> calendarModels;
  private String username;
  private String password;

  public UserModel(long id, String username, String password) {
    this.id = id;
    this.username = username;
    this.password = password;
  }

  public UserModel() {
  }

  public long getId() {
    return id;
  }
//Other Getters and Setters

我的CalendarModel:

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class CalendarModel {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToOne(cascade = CascadeType.MERGE)
  private UserModel userModel;
  private String googleId;
  private String summary;

  public CalendarModel() {
  }

  public CalendarModel(UserModel userModel, String googleId, String summary) {
    this.userModel = userModel;
    this.googleId = googleId;
    this.summary = summary;
  }

  public Long getId() {
    return id;
  }
//Other Getters and Setters

我的带有端点的RestController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

  private UserServiceImpl service;

  @Autowired
  public UserController(UserServiceImpl service) {
    this.service = service;
  }

  @GetMapping("/api/users")
  public ResponseEntity<Object> allUser() {
    List<UserModel> userModelList = service.listUsers();
    if (!userModelList.isEmpty() && userModelList != null) {
      return new ResponseEntity<>(userModelList, HttpStatus.OK);
    }
    return new ResponseEntity<>("Error: users not found!", HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

我的UserModelBuilder类用于测试:

public class UserModelBuilder {

  long id = 1;
  String userName = "user";
  String password = "password";

  public UserModelBuilder() {
  }

  public UserModelBuilder withId(long id) {
    this.id = id;
    return this;
  }

  public UserModelBuilder withUsername(String userName) {
    this.userName = userName;
    return this;
  }

  public UserModelBuilder withPassword(String password) {
    this.password = password;
    return this;
  }

  public UserModel build() {
    return new UserModel(id, userName, password);
  }
}

我的测试(当前工作正常):

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.util.Arrays;

import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private UserServiceImpl service;

  @Test
  public void listAllUserTest() throws Exception {

    UserModel firstUser = new UserModelBuilder()
        .withId(1)
        .withPassword("password")
        .withUsername("firstuser")
        .build();
    UserModel secondUser = new UserModelBuilder()
        .withId(2)
        .withPassword("otherpass")
        .withUsername("seconduser")
        .build();

    Mockito.when(service.listUsers()).thenReturn(Arrays.asList(firstUser, secondUser));

    MvcResult mvcResult = mockMvc.perform(
        MockMvcRequestBuilders.get("/api/users")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$", hasSize(2)))
        .andExpect(jsonPath("$[0].id", is(1)))
        .andExpect(jsonPath("$[0].password", is("password")))
        .andExpect(jsonPath("$[0].username", is("firstuser")))
        .andExpect(jsonPath("$[1].id", is(2)))
        .andExpect(jsonPath("$[1].password", is("otherpass")))
        .andExpect(jsonPath("$[1].username", is("seconduser")))
        .andExpect(status().isOk())
        .andDo(print())
        .andReturn();
    Mockito.verify(service).listUsers();
  }
}

先谢谢您! :)

0 个答案:

没有答案