如何在 spring 启动测试中插入高级数据?

how can i insert advanced data in spring boot test?

我正在 spring 引导中编写测试代码。

但是,我的测试代码没有使用@Before 方法保存数据。

如果我请求'/v1/stay/,它return空数组...

你能解释一下我的代码有什么问题吗?

这是我的测试代码。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StayControllerTest {
  @MockBean
  private StayService stayService;
  @Autowired
  private MockMvc mockMvc;

  // givenStay method is the method generating dummy data
  @Before
  public void before() {
    stayService.save(givenStay1());
    stayService.save(givenStay2());
    stayService.save(givenStay3());
    stayService.save(givenStay4());
    stayService.save(givenStay5());
  }

    @Test
  @Transactional
  void showStayList() throws Exception {

    List<StayReq> original = new ArrayList<>();
    original.add(givenStay1());
    original.add(givenStay2());
    original.add(givenStay3());
    original.add(givenStay4());
    original.add(givenStay5());

    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/v1/stay")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print())
            .andReturn();

    System.out.println(result.getResponse());
  }
}

下面的代码块是我的 StayController 和 StayService

@RestController
@ApiV1
@RequiredArgsConstructor
public class StayController {
  private final StayService stayService;
  private final ApiService apiService;

  @GetMapping("/stay")
  public ResponseEntity<Response> stayList() {
    return apiService.okResponse(stayService.getList());
  }
}
@Service
@RequiredArgsConstructor
public class StayService {
  private final StayRepository stayRepository;
  private final RoomRepository roomRepository;

  public List<StayRes> getList() {
    return stayRepository.findAll().stream().map(StayRes::new).collect(Collectors.toList());
  }
  @Transactional
  public void save(StayReq stayReq) {
    stayRepository.save(stayReq.toEntity());
  }
}

您注入了模拟,而不是 'real' 服务。如果您想使用 'real' 服务 - 您需要将 @MockBean 注释替换为 @Autowired 注释。

或者 - 您可以在测试方法中配置 mock 以 return 一些预定义的数据。