Refactor Velocity example

This commit is contained in:
Grzegorz Piwowarek 2016-07-26 09:22:36 +03:00
parent 09d6e1852f
commit bf78a04b68
7 changed files with 134 additions and 160 deletions

View File

@ -1,29 +1,24 @@
package com.baeldung.mvc.velocity.controller;
import java.util.List;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import java.util.List;
@Controller
@RequestMapping("/")
public class MainController {
@Controller @RequestMapping("/") public class MainController {
private final ITutorialsService tutService;
@Autowired
public MainController(ITutorialsService tutService) {
@Autowired public MainController(ITutorialsService tutService) {
this.tutService = tutService;
}
@RequestMapping(method = RequestMethod.GET)
public String listTutorialsPage(Model model) {
@RequestMapping(method = RequestMethod.GET) public String listTutorialsPage(Model model) {
List<Tutorial> list = tutService.listTutorials();
model.addAttribute("tutorials", list);
return "index";

View File

@ -14,21 +14,20 @@ public class Tutorial {
this.author = author;
}
public Integer getTutId() {
return tutId;
}
public Integer getTutId() {
return tutId;
}
public String getTitle() {
return title;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getDescription() {
return description;
}
public String getAuthor() {
return author;
}
public String getAuthor() {
return author;
}
}

View File

@ -1,44 +1,39 @@
package com.baeldung.mvc.velocity.spring.config;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.Set;
public class MainWebAppInitializer implements WebApplicationInitializer {
/**
* Register and configure all Servlet container components necessary to
* power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
/**
* Register and configure all Servlet container components necessary to
* power the web application.
*/
@Override public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class, SpringConfig.class);
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class, SpringConfig.class);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",
new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due "
+ "to an existing mapping. This is a known issue under Tomcat versions "
+ "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}

View File

@ -5,11 +5,9 @@ import org.springframework.context.annotation.Configuration;
import com.baeldung.mvc.velocity.service.TutorialsService;
@Configuration
public class SpringConfig {
@Configuration public class SpringConfig {
@Bean
public TutorialsService tutService(){
return new TutorialsService();
@Bean public TutorialsService tutService() {
return new TutorialsService();
}
}

View File

@ -11,27 +11,21 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.baeldung.mvc.velocity.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
@Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller" }) public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
@Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver viewResolver() {
@Bean public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
bean.setCache(true);
bean.setPrefix("/WEB-INF/views/");
@ -39,9 +33,8 @@ public class WebConfig extends WebMvcConfigurerAdapter {
bean.setSuffix(".vm");
return bean;
}
@Bean
public VelocityConfigurer velocityConfig() {
@Bean public VelocityConfigurer velocityConfig() {
VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
velocityConfigurer.setResourceLoaderPath("/");
return velocityConfigurer;

View File

@ -1,18 +1,9 @@
package com.baeldung.mvc.velocity.test;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import java.util.Arrays;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import com.baeldung.mvc.velocity.spring.config.WebConfig;
import com.baeldung.mvc.velocity.test.config.TestConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -25,48 +16,58 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.ITutorialsService;
import com.baeldung.mvc.velocity.spring.config.WebConfig;
import com.baeldung.mvc.velocity.test.config.TestConfig;
import java.util.Arrays;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
@ContextConfiguration(classes = { TestConfig.class, WebConfig.class })
@WebAppConfiguration
public class DataContentControllerTest {
@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) @WebAppConfiguration public class DataContentControllerTest {
private MockMvc mockMvc;
private MockMvc mockMvc;
@Autowired
private ITutorialsService tutServiceMock;
@Autowired private ITutorialsService tutServiceMock;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
Mockito.reset(tutServiceMock);
@Before public void setUp() {
Mockito.reset(tutServiceMock);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testModel() throws Exception {
@Test public void testModel() throws Exception {
Mockito.when(tutServiceMock.listTutorials())
.thenReturn(Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")));
Mockito.when(tutServiceMock.listTutorials())
.thenReturn(Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")));
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index"))
.andExpect(model().attribute("tutorials", hasSize(2)))
.andExpect(model().attribute("tutorials",
hasItem(allOf(hasProperty("tutId", is(1)), hasProperty("author", is("GuavaAuthor")),
hasProperty("title", is("Guava"))))))
.andExpect(model().attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)),
hasProperty("author", is("AndroidAuthor")), hasProperty("title", is("Android"))))));
mockMvc.perform(get("/"))
.andExpect(status().isOk()).andExpect(view().name("index"))
.andExpect(model().attribute("tutorials", hasSize(2)))
.andExpect(model()
.attribute("tutorials",
hasItem(allOf(hasProperty("tutId", is(1)),
hasProperty("author", is("GuavaAuthor")),
hasProperty("title", is("Guava"))))))
.andExpect(model()
.attribute("tutorials", hasItem(allOf(hasProperty("tutId", is(2)),
hasProperty("author", is("AndroidAuthor")),
hasProperty("title", is("Android"))))));
mockMvc.perform(get("/")).andExpect(xpath("//table").exists());
mockMvc.perform(get("/")).andExpect(xpath("//td[@id='tutId_1']").exists());
}
mockMvc.perform(get("/"))
.andExpect(xpath("//table").exists());
mockMvc.perform(get("/"))
.andExpect(xpath("//td[@id='tutId_1']").exists());
}
}

View File

@ -1,15 +1,9 @@
package com.baeldung.mvc.velocity.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Arrays;
import java.util.List;
import com.baeldung.mvc.velocity.controller.MainController;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.TutorialsService;
import com.baeldung.mvc.velocity.test.config.TestConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
@ -19,54 +13,53 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import com.baeldung.mvc.velocity.controller.MainController;
import com.baeldung.mvc.velocity.domain.Tutorial;
import com.baeldung.mvc.velocity.service.TutorialsService;
import com.baeldung.mvc.velocity.test.config.TestConfig;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
//@ContextConfiguration(locations = {"classpath:mvc-servlet.xml"})
@ContextConfiguration(classes = {TestConfig.class})
@ContextConfiguration(classes = { TestConfig.class })
public class NavigationControllerTest {
private MainController mainController = new MainController(Mockito.mock(TutorialsService.class));
private final Model model = new ExtendedModelMap();
private MainController mainController = new MainController(Mockito.mock(TutorialsService.class));
@Test
public void shouldGoToTutorialListView() {
Mockito.when(mainController.getTutService().listTutorials())
.thenReturn(createTutorialList());
private final Model model = new ExtendedModelMap();
final String view = mainController.listTutorialsPage(model);
final List<Tutorial> tutorialListAttribute = (List<Tutorial>) model.asMap().get("tutorials");
assertEquals("index", view);
assertNotNull(tutorialListAttribute);
}
@Test
public void testContent() throws Exception{
@Test public void shouldGoToTutorialListView() {
Mockito.when(mainController.getTutService().listTutorials()).thenReturn(createTutorialList());
final String view = mainController.listTutorialsPage(model);
final List<Tutorial> tutorialListAttribute = (List<Tutorial>) model.asMap().get("tutorials");
assertEquals("index", view);
assertNotNull(tutorialListAttribute);
}
@Test public void testContent() throws Exception {
List<Tutorial> tutorials = Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
);
Mockito.when(mainController.getTutService().listTutorials()).thenReturn(tutorials);
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
Mockito.when(mainController.getTutService().listTutorials())
.thenReturn(tutorials);
String view = mainController.listTutorialsPage(model);
verify(mainController.getTutService(), times(1)).listTutorials();
verifyNoMoreInteractions(mainController.getTutService());
assertEquals("index", view);
assertEquals(tutorials, model.asMap().get("tutorials"));
}
private static List<Tutorial> createTutorialList() {
return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description"));
assertEquals("index", view);
assertEquals(tutorials, model.asMap().get("tutorials"));
}
private static List<Tutorial> createTutorialList() {
return Arrays.asList(new Tutorial(1, "TestAuthor", "Test Title", "Test Description"));
}
}