测试Spring Portlet MVC 中的Controller有两种方法,一种是用mock对象,一种是用TestContext框架
测试1:用mock 对象测试Controller。我们把所有Controller用到或者依赖的对象全部mock掉。
- public class AddBookControllerTest {
- //这是被测试的Controller类的实例
- private AddBookController addBookController;
- //因为Controller依赖某些Service,所以我们创造这些Service的mock对象
- private BookService bookService= new MockBookService();
- @Before
- public void setUp() {
- addBookController = new AddBookController();
- addBookController.setBookService(bookService);
- }
- @Test
- public void testShowAddBookForm() {
- //这个测试用例测试一个render方法
- //我们首先创造一个RenderResponse的mock对象
- //调用mock对象上的被测试的方法并且比较返回值
- RenderResponse response = new MockRenderResponse();
- assertEquals("addBookForm",
- addBookController.showAddBookForm(response));
- }
- @Test
- public void testAddBook() {
- //这个测试用例测试一个action方法
- Book book = new Book("test book", "test author", 1234567890L);
- MockActionResponse response = new MockActionResponse();
- //我们调用被测试的方法,让它加入一本书
- addBookController.addBook(book,
- new BindException(book, "book"), response,
- new SimpleSessionStatus());
- //比较结果
- assertNotNull(bookService.getBook(1234567890L));
- assertEquals("books", response.getRenderParameter("myaction"));
- }
- }
测试2:我们用TestContext框架来进行测试。
- //@RunWith用来指定运行这些测试的Runner
- @RunWith(SpringJUnit4ClassRunner.class)
- //@ContextConfiguration用来指定运行这些测试所用到的Spring应用上下文
- @ContextConfiguration(
- locations="classpath:bookCatalogTest-portlet.xml"
- )
- @TestExecutionListeners(value =
- { DependencyInjectionTestExecutionListener.class }
- )
- public class AddBookControllerTestContext extends
- AbstractJUnit4SpringContextTests {
- @Autowired
- @Qualifier("addBookController")
- private AddBookController addBookController;
- @Autowired
- @Qualifier("myBookService")
- private BookService bookService;
- @Autowired
- private Validator validator;
- @Test
- public void testShowAddBookForm() {
- RenderResponse response = new MockRenderResponse();
- assertEquals("addBookForm",
- addBookController.showAddBookForm(response));
- }
- ...
- @Test
- public void testBook() {
- Set<ConstraintViolation<Book>> violations =
- validator.validate(new Book());
- int[] actual = {violations.size()};
- int[] expected = {4};
- assertArrayEquals(expected, actual);
- }
- }
本文转自 charles_wang888 51CTO博客,原文链接:http://blog.51cto.com/supercharles888/845940,如需转载请自行联系原作者