PageRenderTime 228ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/ParkFiftyTestCases/src/com/leopin/parkfifty/admin/unit/tests/AdminJsonUnitTests.java

https://github.com/gvpinto/leopin
Java | 453 lines | 332 code | 93 blank | 28 comment | 2 complexity | 1b6fed04e00117335787bfd32c366155 MD5 | raw file
  1. package com.leopin.parkfifty.admin.unit.tests;
  2. //import static org.junit.Assert.*;
  3. //import static org.mockito.Matchers.*;
  4. //import static org.mockito.Mockito.*;
  5. import static org.junit.Assert.assertEquals;
  6. import static org.junit.Assert.assertNotNull;
  7. import static org.mockito.Matchers.anyLong;
  8. import static org.mockito.Matchers.anyString;
  9. import static org.mockito.Mockito.mock;
  10. import static org.mockito.Mockito.never;
  11. import static org.mockito.Mockito.times;
  12. import static org.mockito.Mockito.verify;
  13. import static org.mockito.Mockito.when;
  14. import java.util.Set;
  15. import javax.validation.ConstraintViolation;
  16. import org.codehaus.jackson.map.ObjectMapper;
  17. import org.codehaus.jackson.map.type.TypeFactory;
  18. import org.codehaus.jackson.type.JavaType;
  19. import org.junit.Assert;
  20. import org.junit.Before;
  21. import org.junit.Test;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import org.springframework.beans.factory.support.RootBeanDefinition;
  25. import org.springframework.context.MessageSource;
  26. import org.springframework.context.support.ResourceBundleMessageSource;
  27. import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
  28. import org.springframework.mock.web.MockHttpServletRequest;
  29. import org.springframework.mock.web.MockHttpServletResponse;
  30. import org.springframework.mock.web.MockServletConfig;
  31. import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
  32. import org.springframework.web.bind.WebDataBinder;
  33. import org.springframework.web.bind.support.WebBindingInitializer;
  34. import org.springframework.web.context.WebApplicationContext;
  35. import org.springframework.web.context.request.WebRequest;
  36. import org.springframework.web.context.support.GenericWebApplicationContext;
  37. import org.springframework.web.servlet.DispatcherServlet;
  38. import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
  39. import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
  40. import com.leopin.parkfifty.admin.domain.AdminDomain;
  41. import com.leopin.parkfifty.server.controller.AdminController;
  42. import com.leopin.parkfifty.server.service.AdminService;
  43. import com.leopin.parkfifty.shared.domain.Company;
  44. import com.leopin.parkfifty.shared.domain.CompanyUser;
  45. import com.leopin.parkfifty.shared.domain.Location;
  46. import com.leopin.parkfifty.shared.domain.jsonwrapper.NewCompanyWrapper;
  47. import com.leopin.parkfifty.shared.exception.AppException;
  48. public class AdminJsonUnitTests {
  49. private static final Logger LOGGER = LoggerFactory.getLogger(AdminJsonUnitTests.class);
  50. AdminService service = null;
  51. MessageSource messages = null;
  52. Company company = null;
  53. CompanyUser companyUser = null;
  54. DispatcherServlet servlet;
  55. @Before
  56. public void setUp() throws Exception {
  57. service = mock(AdminService.class);
  58. messages = mock(ResourceBundleMessageSource.class);
  59. company = mock(Company.class);
  60. companyUser = mock(CompanyUser.class);
  61. }
  62. @Test
  63. public void testRetrieveCompanyById() {
  64. when(company.getName()).thenReturn("Park Fifty");
  65. when(service.getCompany(anyLong())).thenReturn(company);
  66. AdminController controller = new AdminController(this.service, this.messages);
  67. // ReflectionUtils.setField(ReflectionUtils.findField(AdminController.class, "adminService"), controller, service);
  68. // ReflectionUtils.setField(ReflectionUtils.findField(AdminController.class, "messages"), controller, messages);
  69. assertEquals("Park Fifty", controller.getCompany("1").getName());
  70. verify(service, times(1)).getCompany(anyLong());
  71. verify(service, never()).getCompany(anyString());
  72. }
  73. @Test
  74. public void testRetrieveCompanyByName() {
  75. when(company.getName()).thenReturn("Park Fifty");
  76. when(service.getCompany(anyString())).thenReturn(company);
  77. AdminController controller = new AdminController(this.service, this.messages);
  78. // ReflectionUtils.setField(ReflectionUtils.findField(AdminController.class, "adminService"), controller, service);
  79. // ReflectionUtils.setField(ReflectionUtils.findField(AdminController.class, "messages"), controller, messages);
  80. assertEquals("Park Fifty", controller.getCompany("Park Fifty")
  81. .getName());
  82. verify(service, never()).getCompany(anyLong());
  83. verify(service, times(1)).getCompany(anyString());
  84. }
  85. @Test
  86. public void testForAddCompanyService() {
  87. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  88. validator.afterPropertiesSet();
  89. NewCompanyWrapper newCompanyWrapper = AdminDomain.getNewCompanyWrapper();
  90. when(service.addNewCompany(newCompanyWrapper)).thenReturn(newCompanyWrapper);
  91. AdminController controller = new AdminController(this.service, this.messages);
  92. controller.setValidator(validator);
  93. newCompanyWrapper = controller.addCompany(newCompanyWrapper);
  94. try {
  95. assertEquals(newCompanyWrapper.getCompany().getName(), newCompanyWrapper.getCompany().getName());
  96. assertEquals(newCompanyWrapper.getCompanyUser().getFirstName(), newCompanyWrapper.getCompanyUser().getFirstName());
  97. } catch (AppException e) {
  98. LOGGER.debug((String)e.getPlaceholderValues()[1]);
  99. }
  100. verify(service, times(1)).addNewCompany(newCompanyWrapper);
  101. }
  102. @Test
  103. public void testForAddCompanyUserService() {
  104. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  105. validator.afterPropertiesSet();
  106. companyUser = AdminDomain.getCompanyUser(1L);
  107. when(service.addCompanyUser(companyUser)).thenReturn(companyUser);
  108. AdminController controller = new AdminController(this.service, this.messages);
  109. controller.setValidator(validator);
  110. try {
  111. assertEquals(companyUser.getUserId(), controller.addCompanyUser(companyUser).getUserId());
  112. } catch (AppException e) {
  113. LOGGER.debug((String)e.getPlaceholderValues()[1]);
  114. }
  115. verify(service, times(1)).addCompanyUser(companyUser);
  116. }
  117. @Test(expected=AppException.class)
  118. public void testAddCompanyWithErrors() {
  119. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  120. validator.afterPropertiesSet();
  121. NewCompanyWrapper newCompanyWrapper = AdminDomain.getNewCompanyWrapper();
  122. newCompanyWrapper.getCompany().setEmail("gpintobbant.com");
  123. when(service.addNewCompany(newCompanyWrapper)).thenReturn(newCompanyWrapper);
  124. AdminController controller = new AdminController(this.service, this.messages);
  125. controller.setValidator(validator);
  126. assertEquals(newCompanyWrapper.getCompany().getName(), controller.addCompany(newCompanyWrapper).getCompany().getName());
  127. verify(service, times(0)).addNewCompany(newCompanyWrapper);
  128. }
  129. @Test
  130. public void testGoodCompanyValidation() throws Exception {
  131. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  132. validator.afterPropertiesSet();
  133. Company company = new Company();
  134. company.setCode("THIS1SGOOD");
  135. company.setName("This is a good company");
  136. company.setUrl("https://www.goodcompany.com");
  137. company.setEmail("goodcompany@gmail.com");
  138. company.setPriPhone("9194553262");
  139. company.setSecPhone("");
  140. company.setFax("");
  141. Set<ConstraintViolation<Company>> result = validator.validate(company);
  142. LOGGER.error("Result Size[" + result.size() + "]");
  143. assertEquals(0, result.size());
  144. }
  145. @Test
  146. public void testCompanyInvalidEmail() throws Exception {
  147. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  148. validator.afterPropertiesSet();
  149. Company company = new Company();
  150. company.setCode("THIS1SGOOD");
  151. company.setName("This is a good company");
  152. company.setUrl("https://www.goodcompany.com");
  153. company.setEmail("goodcompany@gmailcom");
  154. company.setPriPhone("9194553262");
  155. company.setSecPhone("");
  156. company.setFax("");
  157. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  158. assertEquals(1, constraintViolations.size());
  159. company.setEmail(null);
  160. constraintViolations = validator.validate(company);
  161. assertEquals(1, constraintViolations.size());
  162. // assertEquals("Invalid email address.", constraintViolations.iterator().next().getMessage());
  163. }
  164. @Test
  165. public void testCompanyInvalidPriPhone() throws Exception {
  166. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  167. validator.afterPropertiesSet();
  168. Company company = new Company();
  169. company.setCode("THIS1SGOOD");
  170. company.setName("This is a good company");
  171. company.setUrl("https://www.goodcompany.com");
  172. company.setEmail("goodcompany@gmail.com");
  173. company.setPriPhone("919455326aqwe");
  174. company.setSecPhone("");
  175. company.setFax("");
  176. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  177. assertEquals(1, constraintViolations.size());
  178. company.setPriPhone(null);
  179. constraintViolations = validator.validate(company);
  180. assertEquals(1, constraintViolations.size());
  181. // assertEquals("Invalid primary phone number. Can be 9 to 15 digits long.", constraintViolations.iterator().next().getMessage());
  182. }
  183. @Test
  184. public void testCompanyInvalidAndShortPhone() throws Exception {
  185. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  186. validator.afterPropertiesSet();
  187. Company company = new Company();
  188. company.setCode("THIS1SGOOD");
  189. company.setName("This is a good company");
  190. company.setUrl("https://www.goodcompany.com");
  191. company.setEmail("goodcompany@gmail.com");
  192. company.setPriPhone("919455326");
  193. company.setSecPhone("");
  194. company.setFax("");
  195. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  196. assertEquals(1, constraintViolations.size());
  197. assertEquals("Invalid primary phone number. Should be 9 to 15 digits long.", constraintViolations.iterator().next().getMessage());
  198. company.setPriPhone(null);
  199. constraintViolations = validator.validate(company);
  200. assertEquals(1, constraintViolations.size());
  201. }
  202. @Test
  203. public void testCompanyInvalidSecPhone() throws Exception {
  204. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  205. validator.afterPropertiesSet();
  206. Company company = new Company();
  207. company.setCode("THIS1SGOOD");
  208. company.setName("This is a good company");
  209. company.setUrl("https://www.goodcompany.com");
  210. company.setEmail("goodcompany@gmail.com");
  211. company.setPriPhone("9194553262");
  212. company.setSecPhone("a");
  213. company.setFax("");
  214. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  215. assertEquals(1, constraintViolations.size());
  216. // assertEquals("Invalid secondary phone number. Can be 9 to 15 digits long.", constraintViolations.iterator().next().getMessage());
  217. company.setSecPhone(null);
  218. constraintViolations = validator.validate(company);
  219. assertEquals(0, constraintViolations.size());
  220. }
  221. @Test
  222. public void testCompanyInvalidFax() throws Exception {
  223. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  224. validator.afterPropertiesSet();
  225. Company company = new Company();
  226. company.setCode("THIS1SGOOD");
  227. company.setName("This is a good company");
  228. company.setUrl("https://www.goodcompany.com");
  229. company.setEmail("goodcompany@gmail.com");
  230. company.setPriPhone("9194553262");
  231. company.setSecPhone("");
  232. company.setFax("a");
  233. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  234. assertEquals(1, constraintViolations.size());
  235. // assertEquals("Invalid fax number. Can be 9 to 15 digits long.", constraintViolations.iterator().next().getMessage());
  236. company.setFax(null);
  237. constraintViolations = validator.validate(company);
  238. assertEquals(0, constraintViolations.size());
  239. }
  240. @Test
  241. public void testCompanyInvalidURL() throws Exception {
  242. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  243. validator.afterPropertiesSet();
  244. Company company = new Company();
  245. company.setCode("THIS1SGOOD");
  246. company.setName("This is a good company");
  247. company.setUrl("https:/goodcompany.com");
  248. company.setEmail("goodcompany@gmail.com");
  249. company.setPriPhone("9194553262");
  250. company.setSecPhone("");
  251. company.setFax("");
  252. Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
  253. assertEquals(1, constraintViolations.size());
  254. company.setUrl(null);
  255. constraintViolations = validator.validate(company);
  256. assertEquals(1, constraintViolations.size());
  257. // assertEquals("Invalid URL address", constraintViolations.iterator().next().getMessage());
  258. // for (ConstraintViolation<Company> cv : result) {
  259. // String path = cv.getPropertyPath().toString();
  260. //
  261. // if ("name".equals(path) || "url".equals(path) || "email".equals(path) || "priPhone".equals(path) || "secPhone".equals(path) || "fax".equals(path) ) {
  262. // assertTrue(cv.getConstraintDescriptor().);
  263. // }
  264. // else {
  265. // fail("Invalid constraint violation with path '" + path + "'");
  266. // }
  267. // }
  268. }
  269. // @Test
  270. public void commandProvidingFormControllerWithCustomEditor() throws Exception {
  271. Company company = new Company();
  272. company.setName("Company without errors");
  273. company.setEmail("gpinto@bbandt.com");
  274. company.setUrl("http://www.bbt.com");
  275. company.setPriPhone("9194553262");
  276. when(service.getCompany(anyLong())).thenReturn(company);
  277. @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
  278. @Override
  279. protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
  280. GenericWebApplicationContext wac = new GenericWebApplicationContext();
  281. // controllerDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
  282. RootBeanDefinition controllerDef = new RootBeanDefinition(AdminController.class);
  283. controllerDef.setAutowireCandidate(true);
  284. controllerDef.getPropertyValues().add("adminService", AdminJsonUnitTests.this.service);
  285. controllerDef.getPropertyValues().add("messages", AdminJsonUnitTests.this.messages);
  286. wac.registerBeanDefinition("controller",controllerDef);
  287. // wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class));
  288. RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
  289. adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer());
  290. adapterDef.getPropertyValues().add("messageConverters", new MappingJacksonHttpMessageConverter());
  291. wac.registerBeanDefinition("handlerAdapter", adapterDef);
  292. RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class);
  293. wac.registerBeanDefinition("handlerMapping", mappingDef);
  294. wac.refresh();
  295. return wac;
  296. }
  297. };
  298. servlet.init(new MockServletConfig());
  299. MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/company/1");
  300. request.addHeader("Accept", "application/json");
  301. MockHttpServletResponse response = new MockHttpServletResponse();
  302. servlet.service(request, response);
  303. LOGGER.info(response.getContentAsString());
  304. }
  305. private static class MyWebBindingInitializer implements WebBindingInitializer {
  306. public void initBinder(WebDataBinder binder, WebRequest request) {
  307. LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean();
  308. vf.afterPropertiesSet();
  309. binder.setValidator(vf);
  310. assertNotNull(request.getLocale());
  311. // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  312. // dateFormat.setLenient(false);
  313. // binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
  314. }
  315. }
  316. @Test
  317. public void testLocationValid() throws Exception {
  318. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  319. validator.afterPropertiesSet();
  320. Location location = AdminDomain.getLocation();
  321. Set<ConstraintViolation<Location>> constraintViolations = validator.validate(location);
  322. printConstraintViolations(constraintViolations);
  323. assertEquals(0, constraintViolations.size());
  324. }
  325. @Test
  326. public void testCompanyUserValid() {
  327. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  328. validator.afterPropertiesSet();
  329. CompanyUser companyUser = AdminDomain.getCompanyUser(1L);
  330. Set<ConstraintViolation<CompanyUser>> constraintViolations = validator.validate(companyUser);
  331. printConstraintViolations(constraintViolations);
  332. assertEquals(0, constraintViolations.size());
  333. }
  334. @Test
  335. public void canDeserializeCompany() {
  336. ObjectMapper mapper = new ObjectMapper();
  337. JavaType javaType = TypeFactory.defaultInstance().constructType(Company.class);
  338. Assert.assertTrue(mapper.canDeserialize(javaType));
  339. }
  340. @Test
  341. public void canDeserializeLocation() {
  342. ObjectMapper mapper = new ObjectMapper();
  343. JavaType javaType = TypeFactory.defaultInstance().constructType(Location.class);
  344. Assert.assertTrue(mapper.canDeserialize(javaType));
  345. }
  346. @Test
  347. public void canDeserializeCompanyUser() {
  348. ObjectMapper mapper = new ObjectMapper();
  349. JavaType javaType = TypeFactory.defaultInstance().constructType(CompanyUser.class);
  350. Assert.assertTrue(mapper.canDeserialize(javaType));
  351. }
  352. private <T> void printConstraintViolations(
  353. Set<ConstraintViolation<T>> constraintViolations) {
  354. if (constraintViolations.size() > 0) {
  355. for (ConstraintViolation<T> constraintViolation : constraintViolations) {
  356. LOGGER.debug(">> " + constraintViolation.getMessage());
  357. }
  358. }
  359. }
  360. }