Reputation: 3574
I'm using Hibernate and the JPA with Spring Boot.
I have a DTO which would collect information from a Contact, which, is envisioned to come from a form from the client side which would could potentially have multiple phones sent:
public class ContactDTO {
private BigInteger userId;
private String contactName;
private Map<String, BigInteger> phones;
// getters and setters
}
I'm imagining the data will be sent in a JSON object in this format:
{phones:[{"mobile":"2325552932"}, {"landline":"2235553329"}, ...]
And I have a controller with a POST method designed to handle that:
@PostMapping(path = "/newContact")
public String createNewContact(@ModelAttribute ContactDTO newContact) {
if (newContact.getPhones() !=null) {
// method that persists phone data
}
// .. use a CRUDRepository object to persist the data to MySQL DB
return "savedContact";
}
I guess my questions are twofold:
I'm using the Spring Boot test, and they look something like this :
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AdditiveControllerShould {
@Autowired
private AdditiveController additiveController;
@Autowired
private MockMvc mockMvc;
@Test
public void saveAnEntryWhenPOSTOnlyUserIdAndContactName() throws Exception {
mockMvc.perform(post("/newContact")
.param("userId", "12345")
.param("contactName", "John Smith"))
// how to run test for the Map<String, BigInteger> ???
.andExpect(status().isOk())
.andExpect(content().string(containsString("savedContact")));
}
}
Upvotes: 1
Views: 2847
Reputation: 5283
Controller :
@PostMapping(value= "/newContact")
public String createNewContact(@RequestBody ContactDTO newContact) {
if (newContact.getPhones() !=null) {
// method that persists phone data
}
// .. use a CRUDRepository object to persist the data to MySQL DB
return "savedContact";
}
Test Class:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AdditiveControllerShould {
@Autowired
private MockMvc mockMvc;
private static final ObjectMapper mapper=new ObjectMapper();
@Test
public void saveAnEntryWhenPOSTOnlyUserIdAndContactName() throws Exception {
Map<String,String> phones=new HashMap<>();
phones.put("phone1", "12345");
Map<String,Object> input=new HashMap<>();
input.put("userId", "123456");
input.put("contactName", "TEST");
input.put("phones", phones);
mockMvc.perform(post("/newContact")
.content(mapper.writeValueAsString(input))
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk());
}
}
output:
CONTACT ContactDTO [userId=123456, contactName=TEST, phones={phone1=12345}]
Upvotes: 4