我有基于SpringMVC和Hibernate的简单应用程序,尝试测试将POST
方法保存到数据库的Customer.class
方法。不想测试数据库,只需要简单的单元测试。测试是绿色的,但感觉仍然不够,我怎么能重构它以使它成为它应该的?
CustomerController.class:
@Controller
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
@PostMapping("/saveCustomer")
public String saveCustomer(@ModelAttribute("customer") Customer theCustomer) {
customerService.saveCustomer(theCustomer);
return "redirect:/customer/list";
}}
CustomerServiceImpl.class:
@Service
public class CustomerServiceImpl implements CustomerService {
@Override
@Transactional
public void saveCustomer(Customer theCustomer) {
customerDAO.saveCustomer(theCustomer);
}
}
CustomerDAOImpl.class:
@Repository
public class CustomerDAOImpl implements CustomerDAO {
@Override
public void saveCustomer(Customer theCustomer) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theCustomer);
}
}
CustomerControllerTest.class:
public class CustomerControllerTest {
@InjectMocks
CustomerController controller;
@Mock
CustomerService mockCustomerService;
@Mock
View mockView;
MockMvc mockMvc;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setSingleView(mockView)
.build();
}
@Test
public void testSaveCustomer() throws Exception {
mockMvc.perform(post("/customer/saveCustomer"))
.andExpect(status().isOk())
.andExpect(view().name("redirect:/customer/list"));
}}
答案 0 :(得分:0)
保存客户等对象的常见错误可能如下:
除了单元测试之外,我强烈推荐Fiddler,因为它看起来像是在使用Windows。
Fiddler将允许您拦截系统发出的每个HTTP请求。这将允许您检查单元测试发出的请求,以及有关POST请求标题,正文等的详细信息。
https://www.telerik.com/fiddler
当特定请求失败并且您需要确切地知道请求与成功请求相比时,此工具是您执行的最后一项工作。