Skip to content

2. Controllers REST

Cliff Maury edited this page Jan 29, 2015 · 4 revisions

Step 7 : Controller REST

  • Ajouter un simple controller REST avec une méthode en GET (classe annotée avec @RestController)
  • Ajouter la configuration Java avec @EnableWebMvc
  • Ajouter la plugin jetty dans le pom.xml
  • Lancer un mvn jetty:run dans la console ou dans l'IDE
  • Tester le controller dans le navigateur

Step 8 : JSON

  • Ajouter la dépendance vers jackson-databind
  • Créer une classe UserView
  • Créer une méthode accessible en GET dans le controlleur retournant un UserView
  • Tester dans le navigateur

Step 9 : Refactoring ApplicationInitializer

  • Refactorer la classe avec AbstractAnnotationConfigDispatcherServletInitializer

Step 10 : TEST des controlleurs REST avec MockitoJUnitRunner (standaloneSetup)

The "standaloneSetup" on the other hand is a little closer to a unit test. It tests one controller at a time, the controller can be injected with mock dependencies manually, and it doesn’t involve loading Spring configuration. Such tests are more focused in style and make it easier to see which controller is being tested, whether any specific Spring MVC configuration is required to work, and so on. The "standaloneSetup" is also a very convenient way to write ad-hoc tests to verify some behavior or to debug an issue.

Step 11 :

  • Créer le test pour un service REST "/users" qui renvoie une liste de UserView
  • Mocker le service UserService avec @Mock
  • Ajouter la dépendance vers hamcrest-all

Step 12 : Test avec WebApplicationContext

  • Copier le test précédent avec les modifications suivantes :

UserControllerWebContextTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class, WebMvcConfig.class,})
@WebAppConfiguration
public class UserControllerWebContextBasedTest {

// see tutorial
// http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-configuration#appcontext-config

private MockMvc mockMvc;

@Inject
private UserService userServiceMock;

@Inject
private WebApplicationContext webApplicationContext;

@Before
public void setup() {
    //We have to reset our mock between tests because the mock objects
    //are managed by the Spring container. If we would not reset them,
    //stubbing and verified behavior would "leak" from one test to another.
    Mockito.reset(userServiceMock);
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

Step 13 : Test client du service REST avec MockRestServiceServer

  • Créer un test avec MockRestServiceServer et RestTemplate

SUITE >> : 3.-Persistence