Skip to content

Commit 4fec928

Browse files
Alex Vargaspivovarit
authored andcommitted
Webapplicationcontext example (eugenp#620)
* An example of a test using a WebAppConfiguration annotation * Giving the test the appropriate formatting
1 parent fb5cc7d commit 4fec928

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.baeldung.web.controller;
2+
3+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
4+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
5+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
6+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
7+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
8+
9+
import org.junit.Before;
10+
import org.junit.Test;
11+
import org.junit.runner.RunWith;
12+
import org.mockito.MockitoAnnotations;
13+
import org.springframework.beans.factory.annotation.Autowired;
14+
import org.springframework.test.context.ContextConfiguration;
15+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
16+
import org.springframework.test.context.web.WebAppConfiguration;
17+
import org.springframework.test.web.servlet.MockMvc;
18+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
19+
import org.springframework.web.context.WebApplicationContext;
20+
21+
import com.baeldung.spring.web.config.WebConfig;
22+
23+
@RunWith(SpringJUnit4ClassRunner.class)
24+
@WebAppConfiguration
25+
@ContextConfiguration(classes = WebConfig.class)
26+
public class EmployeeTest {
27+
28+
@Autowired
29+
private WebApplicationContext webAppContext;
30+
private MockMvc mockMvc;
31+
32+
@Before
33+
public void setup() {
34+
MockitoAnnotations.initMocks(this);
35+
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
36+
}
37+
38+
@Test
39+
public void whenEmployeeGETisPerformed_thenRetrievedStatusAndViewNameAndAttributeAreCorrect() throws Exception {
40+
mockMvc.perform(get("/employee")).andExpect(status().isOk()).andExpect(view().name("employeeHome")).andExpect(model().attributeExists("employee")).andDo(print());
41+
}
42+
}

0 commit comments

Comments
 (0)