z, ? | toggle help (this) |
space, → | next slide |
shift-space, ← | previous slide |
d | toggle debug mode |
## <ret> | go to slide # |
c, t | table of contents (vi) |
f | toggle footer |
r | reload slides |
n | toggle notes |
p | run preshow |
spring-test-mvc
)RestTemplate
TestsApplicationContext
management & cachingJdbcTestUtils
(-SimpleJdbcTestUtils
-)@ContextConfiguration
, @DirtiesContext
@Autowired
@Transactional
, @TransactionConfiguration
, @BeforeTransaction
@WebAppConfiguration
SpringJUnit4ClassRunner
for JUnit 4.5+TestContextManager
for TestNGAbstract(Transactional)[JUnit4|TestNG]SpringContextTests
public class OrderServiceTests {
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderServiceTests {
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class OrderServiceTests {
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // defaults to
// OrderServiceTests-context.xml in same package
public class OrderServiceTests {
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // defaults to
// OrderServiceTests-context.xml in same package
public class OrderServiceTests {
@Autowired
private OrderService orderService;
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // defaults to
// OrderServiceTests-context.xml in same package
@Transactional
public class OrderServiceTests {
@Autowired
private OrderService orderService;
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // defaults to
// OrderServiceTests-context.xml in same package
@Transactional
public class OrderServiceTests {
@Autowired
private OrderService orderService;
@BeforeTransaction
public void verifyInitialDatabaseState() { … }
@Test
public void testOrderService() { … }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // defaults to
// OrderServiceTests-context.xml in same package
@Transactional
public class OrderServiceTests {
@Autowired
private OrderService orderService;
@BeforeTransaction
public void verifyInitialDatabaseState() { … }
@Before
public void setUpTestDataWithinTransaction() { … }
@Test
public void testOrderService() { … }
}
TestContext
ContextLoader
ApplicationContext
TestContextManager
TestContext
TestExecutionListener
SPITestContext
TestExecutionListener
2.5SmartContextLoader
SPI@Configuration
classes or resource locationsContextLoader
3.1spring-test
now depends on junit:junit-dep
@Bean
lite modeWebApplicationContext
ApplicationContextInitializer
<beans ...>
<!-- OrderService is autowired with OrderRepository -->
<context:component-scan base-package="com.example"/>
<bean id="orderRepository" class="org.easymock.EasyMock"
factory-method="createMock"
c:_="com.example.repository.OrderRepository" />
</beans>
public static <T> T createMock(Class<T> toMock) {...}
public static <T> T mock(Class<T> clazz)
public static <T> T proxy(T obj)
MockitoFactoryBean
EasyMockFactoryBean
MockEnvironment
in 3.2MockPropertySource
from 3.1MockClientHttpRequest
MockClientHttpResponse
MockHttpInputMessage
MockHttpOutputMessage
MockServletContext
MockHttpSession
MockFilterChain
MockRequestDispatcher
TransactionManagementConfigurer
@TransactionConfiguration
is now rarely necessarySimpleJdbcTestUtils
in favor of JdbcTestUtils
countRowsInTableWhere()
and dropTables()
in JdbcTestUtils
jdbcTemplate
, countRowsInTableWhere()
, and dropTables()
in
AbstractTransactionalJUnit4SpringContextTests
AbstractTransactionalTestNGSpringContextTests
@Bean
lite mode and annotated classesWebApplicationContext
supportRequest
and Session
scoped beansWebApplicationContext
WebApplicationContext
?
@WebAppConfiguration
ApplicationContext
should be a WebApplicationContext
MockServletContext
"src/main/webapp"
classpath:
prefix is also supported
// defaults to "file:src/main/webapp"
@WebAppConfiguration
// detects "WacTests-context.xml" in same package
// or static nested @Configuration class
@ContextConfiguration
public class WacTests {
//...
}
// file system resource
@WebAppConfiguration("webapp")
// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
public class WacTests {
//...
}
// classpath resource
@WebAppConfiguration("classpath:test-web-resources")
// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
public class WacTests {
//...
}
AbstractGenericWebContextLoader
XmlWebContextLoader
AnnotationConfigWebContextLoader
WebDelegatingSmartContextLoader
SmartContextLoader
3.2WebTestExecutionListener
RequestContextHolder
before each test methodMockHttpServletRequest
MockHttpServletResponse
ServletWebRequest
MockHttpServletResponse
and ServletWebRequest
can be injected into the test instanceTestExecutionListener
2.5TestExecutionListener
3.2@WebAppConfiguration
@ContextConfiguration
public class WacTests {
@Autowired WebApplicationContext wac; // cached
@Autowired MockServletContext servletContext; // cached
@Autowired MockHttpSession session;
@Autowired MockHttpServletRequest request;
@Autowired MockHttpServletResponse response;
@Autowired ServletWebRequest webRequest;
//...
}
WebMergedContextConfiguration
MergedContextConfiguration
@WebAppConfiguration
HttpServletRequest
HttpSession
<beans ...>
<bean id="userService" class="com.example.SimpleUserService"
c:loginAction-ref="loginAction" />
<bean id="loginAction" class="com.example.LoginAction"
c:username="#{request.getParameter('user')}"
c:password="#{request.getParameter('pswd')}"
scope="request">
<aop:scoped-proxy />
</bean>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class RequestScopedBeanTests {
@Autowired UserService userService;
@Autowired MockHttpServletRequest request;
@Test
public void requestScope() {
request.setParameter("user", "enigma");
request.setParameter("pswd", "$pr!ng");
LoginResults results = userService.loginUser();
// assert results
}
}
<beans ...>
<bean id="userService" class="com.example.SimpleUserService"
c:userPreferences-ref="userPreferences" />
<bean id="userPreferences" class="com.example.UserPreferences"
c:theme="#{session.getAttribute('theme')}"
scope="session">
<aop:scoped-proxy />
</bean>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class SessionScopedBeanTests {
@Autowired UserService userService;
@Autowired MockHttpSession session;
@Test
public void sessionScope() throws Exception {
session.setAttribute("theme", "blue");
Results results = userService.processUserPreferences();
// assert results
}
}
ApplicationContextInitializer
ConfigurableApplicationContext
Environment
web.xml
by specifying contextInitializerClasses
via
context-param
for the ContextLoaderListener
init-param
for the DispatcherServlet
@ContextConfiguration
via the initializers
attributeinheritInitializers
attributeApplicationContextInitializer
may configure the entire context
Ordered
interface or the @Order
annotation@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = "/app-config.xml",
initializers = CustomInitializer.class)
public class ApplicationContextInitializerTests {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = "/app-config.xml",
initializers =
{PropertySourceInitializer.class, ProfileInitializer.class})
public class ApplicationContextInitializerTests {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = BaseConfig.class,
initializers = BaseInitializer.class)
public class BaseTest {}
@ContextConfiguration(
classes = ExtendedConfig.class,
initializers = ExtendedInitializer.class)
public class ExtendedTest extends BaseTest {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = BaseConfig.class,
initializers = BaseInitializer.class)
public class BaseTest {}
@ContextConfiguration(
classes = ExtendedConfig.class,
initializers = ExtendedInitializer.class,
inheritInitializers = false)
public class ExtendedTest extends BaseTest {}
@ContextConfiguration(initializers = EntireAppInitializer.class)
public class InitializerWithoutConfigFilesOrClassesTest {}
@ContextHierarchy
that contains nested @ContextConfiguration
declarationsname
attribute in @ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
@ContextConfiguration("parent.xml"),
@ContextConfiguration("child.xml")
})
public class AppCtxHierarchyTests {}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(
name="root",
classes = WebAppConfig.class),
@ContextConfiguration(
name="dispatcher",
locations="/spring/dispatcher-config.xml")
})
public class ControllerIntegrationTests {}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")
public abstract class AbstractWebTests {}
@ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml")
public class SoapWebServiceTests extends AbstractWebTests {}
@ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml")
public class RestWebServiceTests extends AbstractWebTests {}
spring-test
as of Spring 3.2 RC1@WebAppConfiguration
DispatcherServlet
RestTemplate
-basedspring-test
TestContext
framework used for loading Spring configMockHttpServletRequest/Response
MockFilterChain
@RequestBody
/@ResponseBody
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
@Before
public void setup() {
this.mvc = webAppContextSetup(this.wac).build();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
@Before
public void setup() {
this.mvc = webAppContextSetup(this.wac).build();
}
@Test
public void getFoo() throws Exception {
this.mvc.perform(get("/foo").accept("application/json"))
.andExpect(status().isOk())
.andExpect(content().mimeType("application/json"))
.andExpect(jsonPath("$.name").value("Lee"));
}
}
MockMvcBuilders.*
, MockMvcRequestBuilders.*
, MockMvcResultMatchers.*
"MockMvc*"
MockMvc
instance ready to perform requests
DispatcherServlet
configTestContext
frameworkDispatcherServlet
configWebApplicationContext
instances
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.example.FooService"/>
</bean>
@Controller
instancesWebApplicationContext
used to configure DispatcherServlet
standaloneSetup(new PersonController()).build()
.mockMvc.perform(post("/persons").param("name", "Joe"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/persons/Joe"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("name"));
@WebAppConfiguration
vs. "Standalone"@WebAppConfiguration
verifies application configMockHttpServletRequest
fields
mockMvc.perform(
post("/hotels/{id}?n={n}", 42, "N"));
mockMvc.perform(
fileUpload("/doc").file("a1", "ABC".getBytes("UTF-8")));
get("/hotels?a=b")
get("/hotels").body("a=b".getBytes("ISO-8859-1"))
get("/hotels").param("a", "b")
get("/app/main/hotels/{id}")
get("").contextPath("/app").servletPath("/main")
get("/hotels/{id}")
MockMvc
webAppContextSetup(this.wac).defaultRequest(get("/")
.accept(MediaType.APPLICATION_JSON)
.param("locale", "en_US"));
.andExpect(..)
perform(..)
MockMvcResultMatchers
provides many choicesmvc.perform("/foo").andDo(print())
MvcResult r = mvc.perform("/foo").andReturn()
MockMvc
webAppContextSetup(this.wac)
.andAlwaysExpect(status.isOk())
.alwaysExpect(content().mimeType("application/xml"))
.alwaysDo(print())
.build();
MockMvc
Spring Security
sample testsHtmlUnit
request-response to MockHttpServletRequest/Response
Selenium
and Geb Spock
on topRestTemplate
Tests
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer =
MockRestServiceServer.createServer(restTemplate);
mockServer.expect(requestTo("/greeting"))
.andRespond(withSuccess("Hello world", "text/plain"));
// use RestTemplate ...
mockServer.verify();
MockRestRequestMatchers.*
and MockRestResponseCreators.*
"MockRest*"
RestTemplate
InstrumentationMockRestServiceServer.createServer(restTemplate)
RestTemplate
with custom ClientHttpRequestFactory
mockServer.expect(..).andExpect(..)
.andReturn(..)
mockServer.expect(..)
RestTemplate
Is UsedRestTemplate
Is UsedmockServer.verify(..)