Hello I really need help testing my routes (if that is even a good practice).
Setup:
Spring Boot
Vaadin (yeeaaa I know ……)
JUnit
I want to test my protected routes, which only admins should be able to get access to. We want to secure these rules with tests. Never thought such a simple idea could be so complicated. Because when I test my protected routes, I always get a 200. Somehow even unknown Routes are returning me a 200.
Vaadin unfortunately do an auto redirect to the login view, if you get an 401/403. I checked it in browser with dev-tools and I really got an 200 in the end, cause after the redirection the loading of the login page is actually successfull. Therefore I disabled it. In browser now I get my expected 401 but in the testing environment I still get my 200.
Unfortunately all tutorials only showing the best case: If X, Y, Z, then expect 200. While I actually want to get the exact opposite. I want to trigger a 401/403 by trying to get access to a protected route with a wrong user role. I want or should I better say: I should not get an 200 … I should get a 401 or 403.
If you could imagine how many thinks I’ve already tried and nothing worked.
My class behind a protected rout I want to test:
@Component
@Scope("prototype")
@RolesAllowed(value = {Role.ROLE_ADMIN})
@Route(value = "methodUsed/create", layout = CustomAppLayout.class)
public class MethodUsedEditView extends VerticalLayout implements BeforeEnterObserver {
...
}
The test class:
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Import(SecurityConfiguration.class)
@WebMvcTest(MethodUsedEditView.class)
public class AuthorizationTest {
@LocalServerPort
private int port;
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = "USER")
public void testAccessingWithoutRole() throws Exception {
mockMvc.perform(get("/methodUsed/create"))
.andExpect(status().isUnauthorized());
}
}
I tried to perform as a specific user, I tried to get access to urls which aren’t even defined. I always get an 200.
Because this route is protected I expect an 401 or 403
user25605111 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.