HelloSpringMVC/src/test/java/djmil/hellomvc/CreetingControllerTests.java
djmil 6740cb9faf SpringSecurity
- secure endpoint
- login page
- in-memory user credentials
- tests
2023-07-28 11:44:25 +02:00

53 lines
1.9 KiB
Java

package djmil.hellomvc;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.security.test.context.support.WithMockUser;
@WebMvcTest(controllers = GreetingController.class)
public class CreetingControllerTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private GreetingService service;
// @Test
// public void shouldReturnDefaultMessage() throws Exception {
// this.mockMvc.perform(get("/greeting"))
// .andDo(print())
// .andExpect(status().isOk())
// .andExpect(content().string(containsString("Hello, World")));
// }
@Test
@WithMockUser
public void greetingShouldReturnMessageFromService() throws Exception {
when(service.nameLength("World")).thenReturn(7);
this.mockMvc.perform(get("/greeting"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Length of your name is 7 characters.")));
}
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void secret() throws Exception {
when(service.nameLength("World")).thenReturn(7);
this.mockMvc.perform(get("/secret"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Greetings user1!")));
}
}