-
Notifications
You must be signed in to change notification settings - Fork 0
2. Controllers 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
- 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
- Refactorer la classe avec
AbstractAnnotationConfigDispatcherServletInitializer
-
Ajouter les dépendances vers mockito-core et json-path
-
Aller voir le tutorial à cette page : http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-configuration#appcontext-config
-
Créer un test du controller avec MockMvc
-
Documentation sur JSONPATH : http://goessner.net/articles/JsonPath/
-
Documentation sur le test : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#spring-mvc-test-framework
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.
- 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
- 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();
}
- Créer un test avec MockRestServiceServer et RestTemplate
SUITE >> : 3.-Persistence