cleanup and testing work

This commit is contained in:
eugenp 2016-10-12 08:00:02 +03:00
parent 2aa2f43c6e
commit eb7650eead
24 changed files with 259 additions and 271 deletions

View File

@ -17,7 +17,7 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.13</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -34,7 +34,6 @@
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build --> <!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>gson</module> <module>gson</module>
<module>gson-jackson-performance</module>
<module>guava</module> <module>guava</module>
<module>guava18</module> <module>guava18</module>
<module>guava19</module> <module>guava19</module>

View File

@ -6,7 +6,7 @@
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<name>spring-mvc-java</name> <name>spring-mvc-java</name>
<packaging>war</packaging> <packaging>war</packaging>
<dependencies> <dependencies>
<!-- Spring --> <!-- Spring -->
<dependency> <dependency>
@ -35,7 +35,7 @@
<artifactId>spring-messaging</artifactId> <artifactId>spring-messaging</artifactId>
<version>${org.springframework.version}</version> <version>${org.springframework.version}</version>
</dependency> </dependency>
<!-- Jackson --> <!-- Jackson -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
@ -56,7 +56,7 @@
<version>1.2</version> <version>1.2</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- AOP --> <!-- AOP -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
@ -80,6 +80,11 @@
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
<version>1.3.1</version> <version>1.3.1</version>
</dependency> </dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>${net.sourceforge.htmlunit}</version>
</dependency>
<!-- Thymeleaf --> <!-- Thymeleaf -->
<dependency> <dependency>
@ -196,7 +201,7 @@
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<excludes> <excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> --> <exclude>**/*IntegrationTest.java</exclude>
</excludes> </excludes>
<systemPropertyVariables> <systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> --> <!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
@ -231,22 +236,22 @@
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version> <org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
<thymeleaf.version>2.1.4.RELEASE</thymeleaf.version> <thymeleaf.version>2.1.4.RELEASE</thymeleaf.version>
<jackson.version>2.7.8</jackson.version> <jackson.version>2.7.8</jackson.version>
<!-- persistence --> <!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version> <hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version> <mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.5</logback.version> <logback.version>1.1.5</logback.version>
<!-- various --> <!-- various -->
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version> <hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
<!-- util --> <!-- util -->
<guava.version>19.0</guava.version> <guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version> <commons-lang3.version>3.4</commons-lang3.version>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
@ -255,6 +260,7 @@
<httpclient.version>4.5</httpclient.version> <httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version> <rest-assured.version>2.9.0</rest-assured.version>
<net.sourceforge.htmlunit>2.23</net.sourceforge.htmlunit> <net.sourceforge.htmlunit>2.23</net.sourceforge.htmlunit>
<!-- maven plugins --> <!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-war-plugin.version>2.6</maven-war-plugin.version>

View File

@ -2,14 +2,14 @@ package com.baeldung.model;
public class Message { public class Message {
private String from; private String from;
private String text; private String text;
public String getText() { public String getText() {
return text; return text;
} }
public String getFrom() { public String getFrom() {
return from; return from;
} }
} }

View File

@ -2,26 +2,26 @@ package com.baeldung.model;
public class OutputMessage { public class OutputMessage {
private String from; private String from;
private String text; private String text;
private String time; private String time;
public OutputMessage(final String from, final String text, final String time) { public OutputMessage(final String from, final String text, final String time) {
this.from = from; this.from = from;
this.text = text; this.text = text;
this.time = time; this.time = time;
} }
public String getText() { public String getText() {
return text; return text;
} }
public String getTime() { public String getTime() {
return time; return time;
} }
public String getFrom() { public String getFrom() {
return from; return from;
} }
} }

View File

@ -10,15 +10,15 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@EnableWebSocketMessageBroker @EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override @Override
public void configureMessageBroker(final MessageBrokerRegistry config) { public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic"); config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app"); config.setApplicationDestinationPrefixes("/app");
} }
@Override @Override
public void registerStompEndpoints(final StompEndpointRegistry registry) { public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS(); registry.addEndpoint("/chat").withSockJS();
} }
} }

View File

@ -22,59 +22,55 @@ import com.baeldung.model.Company;
@Controller @Controller
public class CompanyController { public class CompanyController {
Map<Long, Company> companyMap = new HashMap<>(); Map<Long, Company> companyMap = new HashMap<>();
@RequestMapping(value = "/company", method = RequestMethod.GET) @RequestMapping(value = "/company", method = RequestMethod.GET)
public ModelAndView showForm() { public ModelAndView showForm() {
return new ModelAndView("companyHome", "company", new Company()); return new ModelAndView("companyHome", "company", new Company());
} }
@RequestMapping(value = "/company/{Id}", produces = { "application/json", @RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
"application/xml" }, method = RequestMethod.GET) public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
public @ResponseBody Company getCompanyById(@PathVariable final long Id) { return companyMap.get(Id);
return companyMap.get(Id); }
}
@RequestMapping(value = "/addCompany", method = RequestMethod.POST) @RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String submit(@ModelAttribute("company") final Company company, public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
final BindingResult result, final ModelMap model) { if (result.hasErrors()) {
if (result.hasErrors()) { return "error";
return "error"; }
} model.addAttribute("name", company.getName());
model.addAttribute("name", company.getName()); model.addAttribute("id", company.getId());
model.addAttribute("id", company.getId());
companyMap.put(company.getId(), company); companyMap.put(company.getId(), company);
return "companyView"; return "companyView";
} }
@RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET) @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany( public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) { return new ResponseEntity<>(matrixVars, HttpStatus.OK);
return new ResponseEntity<>(matrixVars, HttpStatus.OK); }
}
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET) @RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public ResponseEntity<Map<String, String>> getCompanyName( public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
@MatrixVariable(value = "name", pathVar = "company") final String name) { final Map<String, String> result = new HashMap<String, String>();
final Map<String, String> result = new HashMap<String, String>(); result.put("name", name);
result.put("name", name); return new ResponseEntity<>(result, HttpStatus.OK);
return new ResponseEntity<>(result, HttpStatus.OK); }
}
@RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/companyResponseBody", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody @ResponseBody
public Company getCompanyResponseBody() { public Company getCompanyResponseBody() {
final Company company = new Company(2, "ABC"); final Company company = new Company(2, "ABC");
return company; return company;
} }
@RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "/companyResponseEntity", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Company> getCompanyResponseEntity() { public ResponseEntity<Company> getCompanyResponseEntity() {
final Company company = new Company(3, "123"); final Company company = new Company(3, "123");
return new ResponseEntity<Company>(company, HttpStatus.OK); return new ResponseEntity<Company>(company, HttpStatus.OK);
} }
} }

View File

@ -31,10 +31,8 @@ public class EmployeeController {
return new ModelAndView("employeeHome", "employee", new Employee()); return new ModelAndView("employeeHome", "employee", new Employee());
} }
@RequestMapping(value = "/employee/{Id}", produces = {"application/json", "application/xml"}, method = RequestMethod.GET) @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
@ResponseBody
Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id); return employeeMap.get(Id);
} }

View File

@ -10,15 +10,15 @@ import org.springframework.web.bind.annotation.RequestParam;
@RequestMapping("/message") @RequestMapping("/message")
public class MessageController { public class MessageController {
@RequestMapping(value = "/showForm", method = RequestMethod.GET) @RequestMapping(value = "/showForm", method = RequestMethod.GET)
public String showForm() { public String showForm() {
return "message"; return "message";
} }
@RequestMapping(value = "/processForm", method = RequestMethod.POST) @RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@RequestParam("message") final String message, final Model model) { public String processForm(@RequestParam("message") final String message, final Model model) {
model.addAttribute("message", message); model.addAttribute("message", message);
return "message"; return "message";
} }
} }

View File

@ -6,8 +6,8 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpRespon
@ControllerAdvice @ControllerAdvice
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpControllerAdvice() { public JsonpControllerAdvice() {
super("callback"); super("callback");
} }
} }

View File

@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopLoggingTest { public class AopLoggingIntegrationTest {
@Before @Before
public void setUp() { public void setUp() {

View File

@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopPerformanceTest { public class AopPerformanceIntegrationTest {
@Before @Before
public void setUp() { public void setUp() {

View File

@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) @ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AopPublishingTest { public class AopPublishingIntegrationTest {
@Before @Before
public void setUp() { public void setUp() {

View File

@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/com/baeldung/aop/beans.xml") @ContextConfiguration("/com/baeldung/aop/beans.xml")
public class AopXmlConfigPerformanceTest { public class AopXmlConfigPerformanceIntegrationTest {
@Before @Before
public void setUp() { public void setUp() {

View File

@ -1,22 +0,0 @@
package com.baeldung.htmlunit;
import org.junit.Assert;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitAndJUnitTest {
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
try (final WebClient webClient = new WebClient()) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.htmlunit;
import java.io.IOException;
import java.net.MalformedURLException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
import org.springframework.web.context.WebApplicationContext;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { TestConfig.class })
public class HtmlUnitAndSpringIntegrationTest {
@Autowired
private WebApplicationContext wac;
private WebClient webClient;
@Before
public void setup() {
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
}
//
@Test
public void givenAMessage_whenSent_thenItShows() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
final String text = "Hello world!";
HtmlPage page = webClient.getPage("http://localhost/message/showForm");
System.out.println(page.asXml());
final HtmlTextInput messageText = page.getHtmlElementById("message");
messageText.setValueAttribute(text);
final HtmlForm form = page.getForms().get(0);
final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
final HtmlPage newPage = submit.click();
final String receivedText = newPage.getHtmlElementById("received").getTextContent();
Assert.assertEquals(receivedText, text);
System.out.println(newPage.asXml());
}
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
try (final WebClient client = new WebClient()) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}
}

View File

@ -1,79 +0,0 @@
package com.baeldung.htmlunit;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
import org.springframework.web.context.WebApplicationContext;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { TestConfig.class })
public class HtmlUnitAndSpringTest {
@Autowired
private WebApplicationContext wac;
private WebClient webClient;
@Before
public void setup() {
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
}
@Test
@Ignore
public void givenAMessage_whenSent_thenItShows() {
final String text = "Hello world!";
HtmlPage page;
try {
page = webClient.getPage("http://localhost/message/showForm");
System.out.println(page.asXml());
final HtmlTextInput messageText = page.getHtmlElementById("message");
messageText.setValueAttribute(text);
final HtmlForm form = page.getForms().get(0);
final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
final HtmlPage newPage = submit.click();
final String receivedText = newPage.getHtmlElementById("received").getTextContent();
Assert.assertEquals(receivedText, text);
System.out.println(newPage.asXml());
} catch (FailingHttpStatusCodeException | IOException e) {
e.printStackTrace();
}
}
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
try (final WebClient client = new WebClient()) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.htmlunit;
import org.junit.Assert;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitTest {
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception {
try (final WebClient webClient = new WebClient()) {
webClient.getOptions().setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}
}

View File

@ -10,31 +10,31 @@ import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitWebScraping { public class HtmlUnitWebScraping {
public static void main(final String[] args) throws Exception { public static void main(final String[] args) throws Exception {
try (final WebClient webClient = new WebClient()) { try (final WebClient webClient = new WebClient()) {
webClient.getOptions().setCssEnabled(false); webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setJavaScriptEnabled(false);
final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive");
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0);
System.out.println("Entering: " + latestPostLink.getHrefAttribute()); System.out.println("Entering: " + latestPostLink.getHrefAttribute());
final HtmlPage postPage = latestPostLink.click(); final HtmlPage postPage = latestPostLink.click();
final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0);
System.out.println("Title: " + heading1.getTextContent()); System.out.println("Title: " + heading1.getTextContent());
final List<HtmlHeading2> headings2 = (List<HtmlHeading2>) postPage.getByXPath("//h2"); final List<HtmlHeading2> headings2 = (List<HtmlHeading2>) postPage.getByXPath("//h2");
final StringBuilder sb = new StringBuilder(heading1.getTextContent()); final StringBuilder sb = new StringBuilder(heading1.getTextContent());
for (final HtmlHeading2 h2 : headings2) { for (final HtmlHeading2 h2 : headings2) {
sb.append("\n").append(h2.getTextContent()); sb.append("\n").append(h2.getTextContent());
} }
System.out.println(sb.toString()); System.out.println(sb.toString());
} }
} }
} }

View File

@ -15,28 +15,28 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@ComponentScan(basePackages = { "com.baeldung.web.controller" }) @ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class TestConfig extends WebMvcConfigurerAdapter { public class TestConfig extends WebMvcConfigurerAdapter {
@Bean @Bean
public ViewResolver thymeleafViewResolver() { public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine()); viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1); viewResolver.setOrder(1);
return viewResolver; return viewResolver;
} }
@Bean @Bean
public ServletContextTemplateResolver templateResolver() { public ServletContextTemplateResolver templateResolver() {
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html"); templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5"); templateResolver.setTemplateMode("HTML5");
return templateResolver; return templateResolver;
} }
@Bean @Bean
public SpringTemplateEngine templateEngine() { public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver()); templateEngine.setTemplateResolver(templateResolver());
return templateEngine; return templateEngine;
} }
} }

View File

@ -23,7 +23,7 @@ import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = WebConfig.class) @ContextConfiguration(classes = WebConfig.class)
public class EmployeeTest { public class EmployeeMvcIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

@ -1,7 +1,7 @@
package com.baeldung.web.controller; package com.baeldung.web.controller;
import org.junit.Before;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -15,7 +15,7 @@ import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = WebConfig.class) @ContextConfiguration(classes = WebConfig.class)
public class EmployeeTestWithoutMockMvc { public class EmployeeNoMvcIntegrationTest {
@Autowired @Autowired
private EmployeeController employeeController; private EmployeeController employeeController;
@ -25,9 +25,10 @@ public class EmployeeTestWithoutMockMvc {
employeeController.initEmployees(); employeeController.initEmployees();
} }
//
@Test @Test
public void whenInitEmployees_thenVerifyValuesInitiation() { public void whenInitEmployees_thenVerifyValuesInitiation() {
Employee employee1 = employeeController.employeeMap.get(1L); Employee employee1 = employeeController.employeeMap.get(1L);
Employee employee2 = employeeController.employeeMap.get(2L); Employee employee2 = employeeController.employeeMap.get(2L);
Employee employee3 = employeeController.employeeMap.get(3L); Employee employee3 = employeeController.employeeMap.get(3L);

View File

@ -1,6 +1,5 @@
package com.baeldung.web.controller; package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -25,7 +24,7 @@ import com.baeldung.spring.web.config.ApplicationConfig;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfig.class}) @ContextConfiguration(classes = { ApplicationConfig.class })
public class GreetControllerIntegrationTest { public class GreetControllerIntegrationTest {
@Autowired @Autowired
@ -35,7 +34,6 @@ public class GreetControllerIntegrationTest {
private static final String CONTENT_TYPE = "application/json"; private static final String CONTENT_TYPE = "application/json";
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
@ -74,8 +72,8 @@ public class GreetControllerIntegrationTest {
@Test @Test
public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()) this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")); .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!"));
} }
@Test @Test

View File

@ -1,17 +1,19 @@
package com.baeldung.web.controller; package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; public class GreetControllerUnitTest {
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class GreetControllerTest {
private MockMvc mockMvc; private MockMvc mockMvc;
private static final String CONTENT_TYPE = "application/json"; private static final String CONTENT_TYPE = "application/json";
@ -43,19 +45,17 @@ public class GreetControllerTest {
@Test @Test
public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception { public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!"));
.andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!"));
} }
@Test @Test
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception { public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)) this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!"));
.andExpect(jsonPath("$.message").value("Hello World!!!"));
} }
@Test @Test
public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception { public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()) this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE))
.andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1)); .andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1));
} }
} }