Java 如何使用MockMvc测试插入?我是201,但我是409
我对为MVC应用程序编写的测试相当陌生,我正在尝试创建一个简单的测试,用于在数据库中插入用户 我正在使用以下课程: DTO-用户储蓄DTOJava 如何使用MockMvc测试插入?我是201,但我是409,java,spring-boot,testing,Java,Spring Boot,Testing,我对为MVC应用程序编写的测试相当陌生,我正在尝试创建一个简单的测试,用于在数据库中插入用户 我正在使用以下课程: DTO-用户储蓄DTO public class UserSavingDTO { private String name; private String dateOfBirth; private String gender; private String address; private String username; p
public class UserSavingDTO {
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String username;
private String password;
public UserSavingDTO() {
}
public UserSavingDTO(String name, String dateOfBirth, String gender, String address, String username, String password) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.username = username;
this.password = password;
}
}
服务-用户服务
@Service
@Transactional
public class UserService {
@Autowired
EntityManager em;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
DoctorRepository doctorRepository;
public Doctor saveDoctor(UserSavingDTO userSavingDTO) throws ParseException {
Role role = new Role();
/*role.setName("ROLE_PATIENT");
roleRepo.save(role);*/
role = roleRepository.findByName("ROLE_DOCTOR");
Collection<Role> roleCollection = new ArrayList<Role>();
roleCollection.add(role);
Doctor doctor = new Doctor();
doctor.setId(UUID.randomUUID().toString());
doctor.setName(userSavingDTO.getName());
doctor.setDateOfBirth(DateUtils.getPrettyDateStringForSQLDate(userSavingDTO.getDateOfBirth()));
doctor.setGender(userSavingDTO.getGender());
doctor.setAddress(userSavingDTO.getAddress());
doctor.setUsername(userSavingDTO.getUsername());
doctor.setPassword(userSavingDTO.getGender());
doctor.setRoles(roleCollection);
return doctorRepository.save(doctor);
}
}
跑步
@SpringBootApplication
@Validated
public class Run extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Run.class);
}
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SpringApplication.run(Run.class, args);
}
}
测试-UserControllerUnitTest
public class UserControllerUnitTest extends RunTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService service;
@Test
public void insertDoctorTest() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
UserSavingDTO doctorDTO = new UserSavingDTO("Test Name", "26/10/2020", "Test Gender", "Test Address", "Test Username", "test");
mockMvc.perform(post("/register")
.content(objectMapper.writeValueAsString(doctorDTO))
.contentType("application/json"))
.andExpect(status().isOk());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Run.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-test.properties")
@AutoConfigureMockMvc
public class RunTest {
@Test
public void contextLoads() {
assert true ;
}
}
测试-运行测试
public class UserControllerUnitTest extends RunTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService service;
@Test
public void insertDoctorTest() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
UserSavingDTO doctorDTO = new UserSavingDTO("Test Name", "26/10/2020", "Test Gender", "Test Address", "Test Username", "test");
mockMvc.perform(post("/register")
.content(objectMapper.writeValueAsString(doctorDTO))
.contentType("application/json"))
.andExpect(status().isOk());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Run.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-test.properties")
@AutoConfigureMockMvc
public class RunTest {
@Test
public void contextLoads() {
assert true ;
}
}
当我在Postman中运行请求时,一切都相应地工作,正如预期的那样:
当我运行提供的测试时,测试失败,代码为409:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /register
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"140"]
Body = {"name":"Test Name","dateOfBirth":"26/10/2020","gender":"Test Gender","address":"Test Address","username":"Test Username","password":"test"}
Session Attrs = {}
Handler:
Type = ro.tuc.ds2020.controllers.RegistrationController
Method = ro.tuc.ds2020.controllers.RegistrationController#createDoctor(UserSavingDTO)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 409
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json"]
Content type = application/json
Body = {"message":"Troubles saving it into the database!","optionPaneType":"WARNING_MESSAGE"}
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :409
我无法准确指出我做的与邮递员测试有什么不同。为什么我在测试中得到一个响应,即我在将其保存到数据库时遇到问题,这意味着doctor为null,而我在Postman中为属性输入相同的值,而doctor没有得到null值