五、创建控制器controller
@RestController
@RequestMapping("/dept")
public class DeptController {
@Autowired
private DeptRepository deptRepository;
@RequestMapping(value = "/findAll", method = {RequestMethod.POST})
public List<DeptDTO> findAllDept(){
return deptRepository.findAll(); //findAll是jpa提供的查询接口
}
@RequestMapping(value="/addDept", method={RequestMethod.POST})
public DeptDTO saveDept(@RequestBody DeptDTO deptDTO){
deptRepository.save(deptDTO);
return deptDTO;
}
}
六、测试controller
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {JpaApplication.class}) //是该项目的启动类
@WebAppConfiguration
@ContextConfiguration
public class DeptControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Test
public void testQuery() throws Exception {
MvcResult result=mvc.perform(MockMvcRequestBuilders.post("/dept/findAll")).andReturn();
MockHttpServletResponse response = result.getResponse();
String content = response.getContentAsString();
List<DeptDTO> deptDTOS = JSON.parseArray(content, DeptDTO.class);
for(DeptDTO deptDTO : deptDTOS){
System.out.println(deptDTO.getdName());
}
}
@Test
public void testAdd() throws Exception {
DeptDTO deptDto = new DeptDTO();
deptDto.setdName("海盗船");
deptDto.setDbSource("cloudDB1");
System.out.println(JSON.toJSONString(deptDto));
MvcResult result=mvc.perform(MockMvcRequestBuilders.post("/dept/addDept")
.contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(deptDto)))
.andReturn();
MockHttpServletResponse response = result.getResponse();
String content = response.getContentAsString();
DeptDTO deptDTO = JSON.parseObject(content, DeptDTO.class);
System.out.println(deptDTO.getDeptNo());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。










