The following snippets should be applied to SpringBoot since SpringMVC has a differente logic about it.
With the follogin @annottation
s it will be possible to execute most of the tests,
however if the intention is to test restricted access to certain method calls,
using @PreAuthorize
, @PostAuthorized
or @Secured
, other approach will be necessery.
WebContext
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClassToBeTested.class)
public class StandardUnitTest {
// ... tests
}
WebContext
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ClassToBeTested.class)
@AutoConfigureMockMvc
public class StandardUnitTest {
// ... tests
@Autowired
private MockMvc mvc;
}
MockMvc
@Test
public void exampleTest() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Hello World"));
Authentication
User
@Test
@Transactional
\!h @WithMockUser(username = "user", authorities = 'ROLE_USER')
public void createInstitutionWithoutProperAuthority() throws Exception {
int databaseSizeBeforeCreate = institutionRepository.findAll().size();
// Create the Institution
institution = createEntityWithContact(em);
InstitutionDTO institutionDTO = institutionMapper.toDto(institution);
mvc.perform(post("/api/institutions")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(institutionDTO)))
// user doesn't have authority, hence the call should be forbidden
\!h .andExpect(status().isForbidden());
// Validate the Institution in the database
List<Institution> institutionList = institutionRepository.findAll();
assertThat(institutionList).hasSize(databaseSizeBeforeCreate);
}
User
annotation@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(username = "admin", authorities = AuthoritiesConstants.ADMIN)
public @interface WithMockAdmin {
}