I have the program which displays the fields with names and the user needs to enter them. How can I test this?
User.java - class for user.
public class User {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
public String getAllInfo() {
return this.firstName + '\n' + this.lastName;
}
//getters and setters
}
Store.java - my controller class.
public class Store {
...
@PostMapping("/cart/index")
public String getInfo(@Valid final User user, final Model model) {
Store.LOGGER.info("{}", user.getAllInfo());
return "cart/index";
}
@GetMapping(value = "cart/index")
public String index(final Model model) {
model.addAttribute("user", new User());
return "cart/index";
}
...
}
My junit test now fails and i'm getting the following message.
null
null
MockHttpServletRequest:
HTTP Method = POST
Request URI = /cart/index
Parameters = {}
Headers = {Accept=[application/json]}
Handler:
Type = app.vlad.store.Store
Method = public java.lang.String app.vlad.store.Store.getInfo(app.vlad.user.User,org.springframework.ui.Model)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = cart/index
View = null
Attribute = user
value = app.vlad.user.User@248deced
errors = []
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = cart/index
Redirected URL = null
Cookies = []
java.lang.AssertionError: No value at JSON path "$.firstName", exception: json can not be null or empty
My test:
StoreTest.java
public class StoreTest {
@Autowired
MockMvc mockMvc;
@Mock
private User user;
@Mock
private Model model;
@Mock
Store store;
@Autowired
List<Products> products;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final Store store = new Store(this.products);
this.mockMvc = MockMvcBuilders.standaloneSetup(store).build();
}
@Test
public void testGetInfo() throws Exception {
this.user.setFirstName("Ivan");
this.user.setLastName("Ivanov");
this.mockMvc
.perform(MockMvcRequestBuilders.post("/cart/index")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("Ivan"))
.andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value("Ivanov"));
}
}