- [Übersicht über Test-Ansätzen für Spring Controller] https://thepracticaldeveloper.com/2017/07/30/guide-spring-boot-controller-tests/
- [Live-Coding zu MVC-Tests (Februar)] https://www.youtube.com/watch?v=TGcE7lEqhN4&list=PLVBvhDBS_eGWm3_N3sx95lGhBWkxuv_Qn&index=17&t=3513s
- [Testing OAuth] https://www.baeldung.com/oauth-api-testing-with-spring-mvc
@RunWith(MockitoJUnitRunner.class)
public class SuperHeroControllerMockMvcStandaloneTest {
private MockMvc mvc;
@Mock
private SuperHeroRepository superHeroRepository;
@InjectMocks
private SuperHeroController superHeroController;
// This object will be magically initialized by the initFields method below.
private JacksonTester<SuperHero> jsonSuperHero;
@Before
public void setup() {
// We would need this line if we would not use MockitoJUnitRunner
// MockitoAnnotations.initMocks(this);
// Initializes the JacksonTester
JacksonTester.initFields(this, new ObjectMapper());
// MockMvc standalone approach
mvc = MockMvcBuilders.standaloneSetup(superHeroController)
.setControllerAdvice(new SuperHeroExceptionHandler())
.addFilters(new SuperHeroFilter())
.build();
}
@Test
public void canRetrieveByIdWhenExists() throws Exception {
// given
given(superHeroRepository.getSuperHero(2))
.willReturn(new SuperHero("Rob", "Mannon", "RobotMan"));
// when
MockHttpServletResponse response = mvc.perform(
get("/superheroes/2")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonSuperHero.write(new SuperHero("Rob", "Mannon", "RobotMan")).getJson()
);
}