|
| 1 | +package com.baeldung.htmlunit; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.junit.Assert; |
| 6 | +import org.junit.Before; |
| 7 | +import org.junit.Ignore; |
| 8 | +import org.junit.Test; |
| 9 | +import org.junit.runner.RunWith; |
| 10 | +import org.springframework.beans.factory.annotation.Autowired; |
| 11 | +import org.springframework.test.context.ContextConfiguration; |
| 12 | +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; |
| 13 | +import org.springframework.test.context.web.WebAppConfiguration; |
| 14 | +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; |
| 15 | +import org.springframework.web.context.WebApplicationContext; |
| 16 | + |
| 17 | +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; |
| 18 | +import com.gargoylesoftware.htmlunit.WebClient; |
| 19 | +import com.gargoylesoftware.htmlunit.html.HtmlForm; |
| 20 | +import com.gargoylesoftware.htmlunit.html.HtmlPage; |
| 21 | +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; |
| 22 | +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; |
| 23 | + |
| 24 | +@RunWith(SpringJUnit4ClassRunner.class) |
| 25 | +@WebAppConfiguration |
| 26 | +@ContextConfiguration(classes = { TestConfig.class }) |
| 27 | +public class HtmlUnitAndSpringTest { |
| 28 | + |
| 29 | + @Autowired |
| 30 | + private WebApplicationContext wac; |
| 31 | + |
| 32 | + private WebClient webClient; |
| 33 | + |
| 34 | + @Before |
| 35 | + public void setup() { |
| 36 | + webClient = MockMvcWebClientBuilder |
| 37 | + .webAppContextSetup(wac).build(); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void givenAMessage_whenSent_thenItShows() throws Exception { |
| 42 | + String text = "Hello world!"; |
| 43 | + HtmlPage page; |
| 44 | + |
| 45 | + String url = "http://localhost/message/showForm"; |
| 46 | + page = webClient.getPage(url); |
| 47 | + |
| 48 | + HtmlTextInput messageText = page.getHtmlElementById("message"); |
| 49 | + messageText.setValueAttribute(text); |
| 50 | + |
| 51 | + HtmlForm form = page.getForms().get(0); |
| 52 | + HtmlSubmitInput submit = form.getOneHtmlElementByAttribute( |
| 53 | + "input", "type", "submit"); |
| 54 | + HtmlPage newPage = submit.click(); |
| 55 | + |
| 56 | + String receivedText = newPage.getHtmlElementById("received") |
| 57 | + .getTextContent(); |
| 58 | + |
| 59 | + Assert.assertEquals(receivedText, text); |
| 60 | + } |
| 61 | +} |
0 commit comments