[英]how can i insert advanced data in spring boot test?
I'm making test code in spring boot.我正在 spring 引导中制作测试代码。
But, my test code doesn't save the data using @Before method.但是,我的测试代码没有使用@Before 方法保存数据。
If i request to '/v1/stay/, it return empty array...如果我请求'/v1/stay/,它返回空数组...
Please can you explain what is wrong with my code?请你解释一下我的代码有什么问题吗?
Here is my test code.这是我的测试代码。
@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());
}
}
And below code blocks are my StayController and StayService下面的代码块是我的 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());
}
}
You injected a mock, not a 'real' service.您注入了模拟服务,而不是“真实”服务。 If you want to use a 'real' service - you need to replace
@MockBean
annotation with @Autowired
annotation.如果您想使用“真正的”服务 - 您需要将
@MockBean
注释替换为@Autowired
注释。
Or alternatively - you can configure mock in the test method to return some predefined data.或者 - 您可以在测试方法中配置 mock 以返回一些预定义的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.