method2testcases
stringlengths
118
6.63k
### Question: GirlController { @PutMapping("/{id}") public Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setId(id); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void updateGirlById() throws Exception { int id = 3; MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "C"); params.add("age", "22"); String response = mockMvc.perform(put("/girls/" + id) .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
### Question: GirlController { @DeleteMapping("/{id}") public void removeGirl(@PathVariable("id") Integer id) { girlRepository.deleteById(id); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void removeGirl() throws Exception { int id = 2; String response = mockMvc.perform(delete("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: GirlController { @GetMapping("/age/{age}") public List<Girl> listGirlByAge(@PathVariable("age") Integer age) { return girlRepository.findByAge(age); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void listGirlByAge() throws Exception { int age = 8; String response = mockMvc.perform(get("/girls/age/" + age) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<List<Girl>> typeReference = new TypeReference<List<Girl>>() { }; List<Girl> list = objectMapper.readValue(response, typeReference); System.out.println(list); }
### Question: GirlController { @PostMapping("/two") public void saveGirlTwo() { girlService.saveTwo(); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void saveGirlTwo() throws Exception { String response = mockMvc.perform(post("/girls/two") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: TodoRepository { public void save(TodoItem item){ items.put(item.getName(),item); } void save(TodoItem item); TodoItem query(String name); }### Answer: @Test public void saveTest(){ TodoItem todoItem = new TodoItem("imooc"); repository.save(todoItem); Assert.assertNull(repository.query(todoItem.getName())); }
### Question: MailService { public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); message.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }### Answer: @Test public void sendSimpleMail() { this.mailService.sendSimpleMail(TO, "这是第一封邮件", "大家好,这是我的第一封邮件"); }
### Question: MailService { public void sendHtmlMail(String to, String subject, String content) throws Exception { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }### Answer: @Test public void sendHtmlMail() throws Exception { StringBuilder content = new StringBuilder(128); content.append("<html\n>"); content.append("<body>\n"); content.append("<h3> Hello World!这是一封Html邮件</h3>\n"); content.append("</body>\n"); content.append("</html>"); this.mailService.sendHtmlMail(TO, "这是一封html邮件", content.toString()); } @Test public void sendTemplateMail() throws Exception { Context context = new Context(); context.setVariable("id", "006"); String emailContent = this.templateEngine.process("emailTemplate", context); this.mailService.sendHtmlMail(TO, "这是一封模版邮件", emailContent); }
### Question: MailService { public void sendAttachmentsMail(String to, String subject, String content, String[] filePaths) throws Exception { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file; for (String filePath : filePaths) { file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); helper.addAttachment(fileName, file); } helper.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }### Answer: @Test public void sendAttachmentsMail() throws Exception { String filePath = "d:\\48-boot-mail-hello.zip"; this.mailService.sendAttachmentsMail(TO, "这是一封带附件的邮件", "这是一封带附件的邮件内容", new String[]{filePath}); }
### Question: BindController { @RequestMapping(value = "/array") public String array(String[] name) { StringBuilder stringBuilder = new StringBuilder(); for (String item : name) { stringBuilder.append(item).append(" "); } return stringBuilder.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void array() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("name", "Tom,Lucy"); String response = mockMvc.perform(get("/array") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: MailService { public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) { logger.info("发送图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId); MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper; try { helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, file); helper.setFrom(from); this.mailSender.send(message); logger.info("发送图片邮件成功!"); } catch (MessagingException ex) { logger.error("发送图片邮件异常:", ex); } } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }### Answer: @Test public void sendInlineResourceMail() { String rscPath = "d:\\thumb.jpg"; String rscId = "img001"; StringBuilder content = new StringBuilder(128); content.append("<html\n>"); content.append("<body>\n"); content.append("<h3> 这是有图片的邮件</h3>\n"); content.append("<img src=\'cid:").append(rscId).append("\'></img>\n"); content.append("<img src=\'cid:").append(rscId).append("\'></img>\n"); content.append("</body>\n"); content.append("</html>"); this.mailService.sendInlineResourceMail(TO, "这是一封带图片的邮件", content.toString(), rscPath, rscId); }
### Question: HelloService { public void sayHello() { System.out.println("Hello World"); } void sayHello(); }### Answer: @Test public void sayHelloTest() { this.helloService.sayHello(); }
### Question: Students { public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } Students(); Students(String sname, String gender, Date birthday, String major); @Override String toString(); Set<Teachers> getTeachers(); void setTeachers(Set<Teachers> teachers); String getSname(); void setSname(String sname); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }### Answer: @Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); Teachers t1 = new Teachers("T001", "张老师"); Teachers t2 = new Teachers("T002", "李老师"); Teachers t3 = new Teachers("T003", "陈老师"); Teachers t4 = new Teachers("T004", "刘老师"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); Set<Teachers> set1 = new HashSet<>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
### Question: Students { public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } Students(); Students(String sname, String gender, Date birthday, String major); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); Set<Teachers> getTeachers(); void setTeachers(Set<Teachers> teachers); String getSname(); void setSname(String sname); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }### Answer: @Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); Teachers t1 = new Teachers("T001", "张老师"); Teachers t2 = new Teachers("T002", "李老师"); Teachers t3 = new Teachers("T003", "陈老师"); Teachers t4 = new Teachers("T004", "刘老师"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); Set<Teachers> set1 = new HashSet<>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
### Question: Students { public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } Students(); Students(String sname, String gender, Date birthday, String major); @Override String toString(); String getSname(); void setSname(String sname); ClassRoom getClassRoom(); void setClassRoom(ClassRoom classRoom); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }### Answer: @Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); ClassRoom c1 = new ClassRoom("C001", "软件工程"); ClassRoom c2 = new ClassRoom("C002", "网络工程"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); s1.setClassRoom(c1); s2.setClassRoom(c1); s3.setClassRoom(c2); s4.setClassRoom(c2); session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
### Question: GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girls/{id}") Girl girlFindOne(@PathVariable("id") Integer id); @PutMapping(value = "/girls/{id}") Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping(value = "/girls/{id}") void girlDelete(@PathVariable("id") Integer id); @GetMapping(value = "/girls/age/{age}") List<Girl> girlListByAge(@PathVariable("age") Integer age); @PostMapping(value = "/girls/two") void girlTwo(); @GetMapping(value = "girls/getAge/{id}") void getAge(@PathVariable("id") Integer id); }### Answer: @Test public void girlList() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("abc")); }
### Question: JDBCUtil { public static Connection getConnection() throws Exception { InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(inputStream); String url = properties.getProperty("jdbc.url"); String user = properties.getProperty("jdbc.user"); String password = properties.getProperty("jdbc.password"); String driverClass = properties.getProperty("jdbc.driverClass"); Class.forName(driverClass); Connection connection = DriverManager.getConnection(url, user, password); return connection; } static Connection getConnection(); static void release(ResultSet resultSet, Statement statement, Connection connection); }### Answer: @Test public void testGetConnection() throws Exception { Connection connection = JDBCUtil.getConnection(); Assert.assertNotNull(connection); }
### Question: EmployeeService { @Transactional public void update(Integer id, Integer age) { employeeRepository.update(id, age); } @Transactional void update(Integer id, Integer age); }### Answer: @Test public void testUpdate() { employeeService.update(1, 55); }
### Question: BindController { @RequestMapping(value = "/object") public String object(User user, Admin admin) { return user.toString() + " ### " + admin.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void object() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("name", "Tom"); params.add("age", "20"); params.add("contactInfo.phone", "10086"); params.add("contactInfo.address", "11号"); params.add("admin.name", "Lucy"); params.add("admin.age", "18"); String response = mockMvc.perform(get("/object") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: StudentDAOImpl implements StudentDAO { @Override public List<Student> query() { List<Student> students = new ArrayList<Student>(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "select id, name , age from student"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); Student student = null; while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); student = new Student(); student.setId(id); student.setName(name); student.setAge(age); students.add(student); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.release(resultSet,preparedStatement,connection); } return students; } @Override List<Student> query(); @Override void save(Student student); }### Answer: @Test public void testQuery() { StudentDAO studentDAO = new StudentDAOImpl(); List<Student> students = studentDAO.query(); for (Student student : students) { System.out.println("id:" + student.getId() + " , name:" + student.getName() + ", age:" + student.getAge()); } }
### Question: StudentDAOImpl implements StudentDAO { @Override public void save(Student student) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "insert into student(name, age) values(?,?)"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.setInt(2, student.getAge()); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.release(resultSet,preparedStatement,connection); } } @Override List<Student> query(); @Override void save(Student student); }### Answer: @Test public void testSave() { StudentDAO studentDAO = new StudentDAOImpl(); Student student = new Student(); student.setName("test"); student.setAge(30); studentDAO.save(student); }
### Question: StudentDAOSpringJdbcImpl implements StudentDAO { @Override public List<Student> query() { final List<Student> students = new ArrayList<Student>(); String sql = "select id, name , age from student"; jdbcTemplate.query(sql, new RowCallbackHandler(){ @Override public void processRow(ResultSet rs) throws SQLException { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); Student student = new Student(); student.setId(id); student.setName(name); student.setAge(age); students.add(student); } }); return students; } @Override List<Student> query(); @Override void save(Student student); JdbcTemplate getJdbcTemplate(); void setJdbcTemplate(JdbcTemplate jdbcTemplate); }### Answer: @Test public void testQuery() { List<Student> students = studentDAO.query(); for (Student student : students) { System.out.println("id:" + student.getId() + " , name:" + student.getName() + ", age:" + student.getAge()); } }
### Question: StudentDAOSpringJdbcImpl implements StudentDAO { @Override public void save(Student student) { String sql = "insert into student(name, age) values(?,?)"; jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge()}); } @Override List<Student> query(); @Override void save(Student student); JdbcTemplate getJdbcTemplate(); void setJdbcTemplate(JdbcTemplate jdbcTemplate); }### Answer: @Test public void testSave() { Student student = new Student(); student.setName("test-spring-jdbc"); student.setAge(40); studentDAO.save(student); }
### Question: SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager( @SessionId Provider<Long> sessionIdProvider); Long getSessionId(); }### Answer: @Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals( sessionId2.longValue(), sessionId1.longValue()); }
### Question: DemoService { @Transactional(rollbackFor = Exception.class) public void addUser(String name) { OperationLog log = new OperationLog(); log.setContent("create user:" + name); operationLogDao.save(log); User user = new User(); user.setName(name); userDao.save(user); } @Transactional(rollbackFor = Exception.class) void addUser(String name); }### Answer: @Test public void testWithoutTransaction(){ demoService.addUser("tom"); }
### Question: GirlController { @GetMapping public List<Girl> listGirl() { return girlRepository.findAll(); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void listGirl() throws Exception { String response = mockMvc.perform(get("/girls") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: GirlController { @PostMapping public Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void girlAdd() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "B"); params.add("age", "20"); String response = mockMvc.perform(post("/girls") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: BindController { @RequestMapping(value = "list") public String list(UserListForm userListForm) { return "listSize:" + userListForm.getUsers().size() + userListForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void list() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users[0].name", "Tome"); params.add("users[20].name", "Lucy"); String response = mockMvc.perform(get("/list") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: GirlController { @GetMapping("/{id}") public Girl getGirlById(@PathVariable("id") Integer id) { return girlRepository.findById(id).orElse(null); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void getGirlById() throws Exception { int id = 3; String response = mockMvc.perform(get("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
### Question: GirlController { @PutMapping("/{id}") public Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setId(id); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void updateGirlById() throws Exception { int id = 3; MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "C"); params.add("age", "22"); String response = mockMvc.perform(put("/girls/" + id) .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
### Question: GirlController { @DeleteMapping("/{id}") public void removeGirl(@PathVariable("id") Integer id) { girlRepository.deleteById(id); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void removeGirl() throws Exception { int id = 2; String response = mockMvc.perform(delete("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: GirlController { @GetMapping("/age/{age}") public List<Girl> listGirlByAge(@PathVariable("age") Integer age) { return girlRepository.findByAge(age); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void listGirlByAge() throws Exception { int age = 18; String response = mockMvc.perform(get("/girls/age/" + age) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<List<Girl>> typeReference = new TypeReference<List<Girl>>() { }; List<Girl> list = objectMapper.readValue(response, typeReference); System.out.println(list); }
### Question: GirlController { @PostMapping("/two") public void saveGirlTwo() { girlService.saveTwo(); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }### Answer: @Test public void saveGirlTwo() throws Exception { String response = mockMvc.perform(post("/girls/two") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: SeckillServiceImpl implements SeckillService { @Override public List<Seckill> getSeckillList() { return seckillDao.queryAll(0, 4); } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }### Answer: @Test public void getSeckillList() throws Exception { List<Seckill> list = seckillService.getSeckillList(); logger.info("list={}",list); }
### Question: SeckillServiceImpl implements SeckillService { @Override public Seckill getById(long seckillId) { return seckillDao.queryById(seckillId); } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }### Answer: @Test public void getById() throws Exception { long id = 1000L; Seckill seckill = seckillService.getById(id); logger.info("seckill={}", seckill); }
### Question: SeckillServiceImpl implements SeckillService { @Override public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) { if (md5 == null || !md5.equals(getMd5(seckillId))) { return new SeckillExecution(seckillId, SeckillStatEnum.DATA_REWRITE); } Date killTime = new Date(); Map<String, Object> map = new HashMap<>(16); map.put("seckillId", seckillId); map.put("phone", userPhone); map.put("killTime", killTime); map.put("result", null); try { seckillDao.killByProcedure(map); int result = MapUtils.getInteger(map, "result", -2); if (result == 1) { SuccessSeckilled sk = successKilledDao.queryByIdWithSeckill(seckillId, userPhone); return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, sk); } else { return new SeckillExecution(seckillId, SeckillStatEnum.stateOf(result)); } } catch (Exception e) { logger.error(e.getMessage(), e); return new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR); } } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }### Answer: @Test public void executeSeckillProcedure(){ long seckillId = 1001L; long phone = 13621254121L; Exposer exposer = seckillService.exportSeckillUrl(seckillId); if(exposer.isExposed()){ String md5 = exposer.getMd5(); SeckillExecution execution = seckillService.executeSeckillProcedure(seckillId,phone,md5); logger.info(execution.getStateInfo()); } }
### Question: BeanAnnotation { public void say(String arg) { System.out.println("BeanAnnotation : " + arg); } void say(String arg); }### Answer: @Test public void testSay() { BeanAnnotation bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.say("This is test."); bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.say("This is test."); }
### Question: BindController { @RequestMapping(value = "set") public String set(UserSetForm userSetForm) { return userSetForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void set() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users[0].name", "Tome"); String response = mockMvc.perform(get("/set") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: BeanAnnotation { void myHashCode() { System.out.println("BeanAnnotation : " + this.hashCode()); } void say(String arg); }### Answer: @Test public void testScpoe() { BeanAnnotation bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); }
### Question: BeanScope { public void say() { System.out.println("BeanScope say : " + this.hashCode()); } void say(); }### Answer: @Test public void testSay() { BeanScope beanScope = super.getBean("beanScope", BeanScope.class); beanScope.say(); BeanScope beanScope2 = super.getBean("beanScope", BeanScope.class); beanScope2.say(); } @Test public void testSay2() { BeanScope beanScope = super.getBean("beanScopeSingleton", BeanScope.class); beanScope.say(); BeanScope beanScope2 = super.getBean("beanScopeSingleton", BeanScope.class); beanScope2.say(); }
### Question: SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager(@SessionId Provider<Long> sessionIdProvider); Long getSessionId(); }### Answer: @Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals(sessionId1.longValue(), sessionId2.longValue()); }
### Question: OrderSender { public void send(Order order) { CorrelationData correlationData = new CorrelationData(); correlationData.setId(order.getMessageId()); this.rabbitTemplate.convertAndSend("order-exchange", "order.a", order, correlationData); } @Autowired OrderSender( RabbitTemplate rabbitTemplate); void send(Order order); }### Answer: @Test public void testSend1() { Order order = new Order(); order.setId("201809062009010001"); order.setName("测试订单1"); order.setMessageId(System.currentTimeMillis() + "$" + UUID.randomUUID().toString().replaceAll("-", "")); this.orderSender.send(order); }
### Question: BindController { @RequestMapping(value = "map") public String map(UserMapForm userMapForm) { return userMapForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void map() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users['x'].name", "Tom"); params.add("users['y'].age", "1"); params.add("users['y'].name", "Lucy"); String response = mockMvc.perform(get("/map") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: BindController { @RequestMapping(value = "json") public String json(@RequestBody User user) { return user.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void json() throws Exception { User user = new User(); user.setName("Jim"); user.setAge(16); ContactInfo contactInfo = new ContactInfo(); contactInfo.setAddress("beijing"); contactInfo.setPhone("10010"); user.setContactInfo(contactInfo); String request = super.objectMapper.writeValueAsString(user); System.out.println(request); String response = mockMvc.perform(post("/json") .contentType(APPLICATION_JSON_UTF8) .content(request)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: BindController { @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) public String xml(@RequestBody Admin admin) { return admin.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void xml() throws Exception { String request = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><admin><name>Jim</name><age>18</age></admin>"; String response = mockMvc.perform(post("/xml") .contentType(APPLICATION_XML_VALUE) .content(request)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: BindController { @RequestMapping(value = "date1") public String date1(Date date1) { return date1.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }### Answer: @Test public void date1() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("date1", "2020-03-14"); String response = mockMvc.perform(get("/date1") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
### Question: ViewPagerAnimator implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (position == 0 && positionOffsetPixels == 0 && !isAnimating()) { onPageSelected(0); } if (isAnimating() && lastPosition != position || positionOffsetPixels == 0) { endAnimation(position); } if (positionOffsetPixels > 0) { beginAnimation(position); } if (isAnimating()) { float fraction = interpolator.getInterpolation(positionOffset); V value = evaluator.evaluate(fraction, startValue, endValue); property.set(value); } lastPosition = position; } ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator); ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator, @NonNull Interpolator interpolator); static ViewPagerAnimator<Integer> ofInt(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Integer> ofArgb(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Number> ofFloat(ViewPager viewPager, Provider<Number> provider, Property<Number> property); @Override void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); @Override void onPageSelected(int position); @Override void onPageScrollStateChanged(int state); void destroy(); void setViewPager(ViewPager viewPager); void setInterpolator(Interpolator newInterpolator); }### Answer: @Test public void givenAStartedIntegerAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { integerAnimator.onPageScrolled(1, 0f, 0); integerAnimator.onPageScrolled(1, 0.1f, 10); integerAnimator.onPageScrolled(0, 0.9f, 90); assertThat(integerProperty.get()).isEqualTo(90); } @Test public void givenAnIdleIntegerAnimation_whenWeDragTheViewPager_thenTheAnimationStarts() { integerAnimator.onPageScrolled(1, 0f, 0); integerAnimator.onPageScrolled(0, 0.9f, 90); assertThat(integerProperty.get()).isEqualTo(90); } @Test public void givenANewlyCreatedIntegerAnimation_whenItIsInitialised_thenThePageIsSet() { integerAnimator.onPageScrolled(0, 0f, 0); verify(integerProperty, times(1)).set(eq(0)); } @Test public void givenAStartedFloatAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { numberAnimator.onPageScrolled(1, 0f, 0); numberAnimator.onPageScrolled(1, 0.1f, 10); numberAnimator.onPageScrolled(0, 0.9f, 90); assertThat(numberProperty.get()).isEqualTo(0.9f); } @Test public void givenAStartedArgbAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { argbAnimator.onPageScrolled(1, 0f, 0); argbAnimator.onPageScrolled(1, 0.1f, 10); argbAnimator.onPageScrolled(0, 0.9f, 90); assertThat(argbProperty.get()).isEqualTo(0xFF1AE500); }
### Question: ViewPagerAnimator implements ViewPager.OnPageChangeListener { public void destroy() { viewPager.removeOnPageChangeListener(this); } ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator); ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator, @NonNull Interpolator interpolator); static ViewPagerAnimator<Integer> ofInt(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Integer> ofArgb(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Number> ofFloat(ViewPager viewPager, Provider<Number> provider, Property<Number> property); @Override void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); @Override void onPageSelected(int position); @Override void onPageScrollStateChanged(int state); void destroy(); void setViewPager(ViewPager viewPager); void setInterpolator(Interpolator newInterpolator); }### Answer: @Test public void givenAnInitialisedIntegerAnimation_whenDestroyIt_thenItIsDetachedFromTheViewPager() { integerAnimator.destroy(); verify(integerViewPager, times(1)).removeOnPageChangeListener(eq(integerAnimator)); }
### Question: RestCurseProvider implements BitcoinCurseProvider { @Override public BitcoinCurse getCurrentCurse() { if(lastCurse == null || ttlIsOver()) { try { lastCurse = requestBitcoinCurse(); } catch (IOException e) { log.error("Error while request bitcoin!", e); lastCurse = new BitcoinCurse(DateTime.now().minusDays(1), null, null); } lastCall = DateTime.now(); } return lastCurse; } @Override BitcoinCurse getCurrentCurse(); static final String ENDPOINT; }### Answer: @Test public void request(){ BitcoinCurse currentCurse = provider.getCurrentCurse(); assertNotNull(currentCurse.getDate()); assertNotNull(currentCurse.getCoin()); assertNotNull(currentCurse.getEuro()); BitcoinCurse currentCurse2 = provider.getCurrentCurse(); assertSame(currentCurse, currentCurse2); }
### Question: SpeechService { public OutputSpeech speechError(Throwable t) { final String speechText; if (t instanceof AlexaExcpetion) { speechText = messageService.de(((AlexaExcpetion)t).getMessageKey()); } else { speechText = messageService.de("event.error"); } return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void speechError(){ CalendarReadException e = new CalendarReadException("error"); final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechError(e); assertEquals("Es tut mir leid. Ich konnte die Termine nicht auslesen.", result.getText()); }
### Question: ReflectionUtils { public static Object call(Method method, Object target, Argument...arguments) { checkArguments(method, arguments); Object[] methodArguments = collectArguments(method, arguments); return org.springframework.util.ReflectionUtils.invokeMethod(method, target, methodArguments); } static Object call(Method method, Object target, Argument...arguments); }### Answer: @Test(expected = IllegalArgumentException.class) public void argumentsNotEnough() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); ReflectionUtils.call(method, toTest); } @Test(expected = IllegalArgumentException.class) public void argumentsNotRight() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); ReflectionUtils.call(method, toTest, new Argument(Long.class, 13L)); } @Test public void exactMatch() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13)); assertEquals("integer13", result); } @Test public void oneOfArgumentsMatches() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(Long.class, 14L)); assertEquals("integer13", result); } @Test public void multipleArgumentsMatches() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(Integer.class, 14)); assertEquals("integer13", result); } @Test public void subClassMatch() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("interfaceMethod", List.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(ArrayList.class, new ArrayList())); assertEquals("interfaceArrayList", result); }
### Question: SpeechService { public OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale) { final String speechText; if(from.getYear() == to.getYear() && from.getDayOfYear() == to.getDayOfYear()) { speechText = messageService.de("event.new.confirm.sameday", from.toString(DAY_FORMAT, locale), from.toString(DATE_YEAR_FORMAT), from.toString(TIME_FORMAT), to.toString(TIME_FORMAT), title); } else { speechText = messageService.de("event.new.confirm", from.toString(DAY_FORMAT, locale), from.toString(DATE_YEAR_FORMAT), from.toString(TIME_FORMAT), to.toString(DAY_FORMAT, locale), to.toString(DATE_YEAR_FORMAT), to.toString(TIME_FORMAT), title); } return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void confirmNewEvent_sameDay() { final String title = "hello world"; final DateTime from = DateTime.parse("2010-08-13T20:15"); final DateTime to = from.plusHours(1); final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.confirmNewEvent(title, from, to, aLocale); assertEquals(String.format("<speak>Kann ich den Termin am %s, den <say-as interpret-as=\"date\" format=\"dmy\">%s</say-as> von %s Uhr bis %s Uhr mit dem Titel \"%s\" speichern?</speak>", "Freitag", "13.08.2010", "20:15", "21:15", title ), result.getSsml()); } @Test public void confirmNewEvent_differentDay() { final String title = "hello world"; final DateTime from = DateTime.parse("2010-08-13T20:15"); final DateTime to = from.plusHours(1).plusDays(1); final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.confirmNewEvent(title, from, to, aLocale); assertEquals(String.format("<speak>Kann ich den Termin von %s, den <say-as interpret-as=\"date\" format=\"dmy\">%s</say-as> um %s Uhr bis %s, den <say-as interpret-as=\"date\" format=\"dm\">%s</say-as> um %s Uhr mit dem Titel \"%s\" speichern?</speak>", "Freitag", "13.08.2010", "20:15", "Samstag", "14.08.2010", "21:15", title ), result.getSsml()); }
### Question: SpeechService { public OutputSpeech speechNewEventSaved(Locale locale) { final String speechText = messageService.de("event.new.saved"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void speechNewEventSaved(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechNewEventSaved(aLocale); assertEquals("OK. Ich habe den Termin gespeichert.", result.getText()); }
### Question: SpeechService { public OutputSpeech speechGeneralConfirmation(Locale locale) { final String speechText = messageService.de("confirm"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void speechGeneralConfirmation(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechGeneralConfirmation(aLocale); assertEquals("OK.", result.getText()); }
### Question: CalendarService { public List<Event> getNextEvents() throws CalendarReadException { final DateTime from = DateTime.now(); final DateTime to = from.plusWeeks(1).plusDays(1).withTimeAtStartOfDay(); return getEvents(from, to); } List<Event> getEvents(DateTime from, DateTime to); List<Event> getNextEvents(); String createEvent( final String calendarName, final String summary, final DateTime from, final DateTime to); }### Answer: @Test public void getNextEvents() throws CalendarReadException { final List<Event> events = new ArrayList<>(); doReturn(events).when(toTest).getEvents(any(), any()); final DateTime now = DateTime.now(); final List<Event> result = toTest.getNextEvents(); ArgumentCaptor<DateTime> timeCap = ArgumentCaptor.forClass(DateTime.class); assertSame(events, result); verify(toTest, times(1)).getEvents(timeCap.capture(), timeCap.capture()); assertTrue(timeCap.getAllValues().get(0).getMillis() - now.getMillis() <= 1000); assertEquals( now.plusDays(1).plusWeeks(1).withTimeAtStartOfDay().toString(), timeCap.getAllValues().get(1).toString()); }
### Question: CalendarService { public List<Event> getEvents(DateTime from, DateTime to) throws CalendarReadException { if(getCalendars() == null) return Collections.emptyList(); try { List<Event> allEvents = new ArrayList<>(); List<Future<List<Event>>> futures = new ArrayList<>(getCalendars().size()); for(CalendarCLIAdapter calendar : getCalendars().values()) { Future<List<Event>> future = executor.submit(() -> { return calendar.readAgenda(from, to).stream() .flatMap(rawEvent -> parser.parseEvent(rawEvent).stream()) .map(vEvent -> mapper.map(vEvent, calendar.getDefaultTimeZone())) .collect(Collectors.toList()); }); futures.add(future); } for(Future<List<Event>> future : futures) { allEvents.addAll(future.get()); } allEvents.sort(Comparator.comparing(Event::getStart)); return allEvents; } catch (Exception e) { throw new CalendarReadException("Could not read calendar.", e); } } List<Event> getEvents(DateTime from, DateTime to); List<Event> getNextEvents(); String createEvent( final String calendarName, final String summary, final DateTime from, final DateTime to); }### Answer: @Test public void getEvents() throws IOException, CalendarReadException { final CalendarCLIAdapter calendarOne = mock(CalendarCLIAdapter.class); final CalendarCLIAdapter calendarTwo = mock(CalendarCLIAdapter.class); final Map<String, CalendarCLIAdapter> calendars = new HashMap<>(); calendars.put("one", calendarOne); calendars.put("two", calendarTwo); doReturn(TimeZone.getTimeZone("UTC")).when(calendarOne).getDefaultTimeZone(); doReturn(TimeZone.getTimeZone("Europe/Berlin")).when(calendarTwo).getDefaultTimeZone(); when(calendarOne.readAgenda(any(), any())) .thenReturn(Arrays.asList("<cal1-event1>", "<cal1-event2>")); when(calendarTwo.readAgenda(any(), any())) .thenReturn(Arrays.asList("<cal2-event1>")); doReturn(calendars).when(toTest).getCalendars(); List<VEvent> cal1Event1 = Arrays.asList(e("cal1e1", DateTime.parse("2000-01-01"))); List<VEvent> cal1Event2 = Arrays.asList(e("cal1e2", DateTime.parse("2010-01-01")), e("cal1e3", DateTime.parse("2000-01-02"))); List<VEvent> cal2Event1 = Arrays.asList(e("cal2e1", DateTime.parse("2000-01-01"))); doReturn(cal1Event1).when(parser).parseEvent(eq("<cal1-event1>")); doReturn(cal1Event2).when(parser).parseEvent(eq("<cal1-event2>")); doReturn(cal2Event1).when(parser).parseEvent(eq("<cal2-event1>")); final DateTime from = DateTime.now(); final DateTime to = DateTime.now().plusDays(1); final List<Event> results = toTest.getEvents(from, to); verify(calendarOne, times(1)).readAgenda(from, to); verify(calendarTwo, times(1)).readAgenda(from, to); assertEquals("cal1e1", results.get(0).getSummary()); assertEquals("cal2e1", results.get(1).getSummary()); assertEquals("cal1e3", results.get(2).getSummary()); assertEquals("cal1e2", results.get(3).getSummary()); }
### Question: CalendarCLIAdapter { public List<String> readAgenda(DateTime from, DateTime to) throws IOException { List<String> subCommands = new ArrayList<>(); subCommands.add("--icalendar"); subCommands.add("calendar"); subCommands.add("agenda"); if(from != null) { subCommands.add("--from-time"); subCommands.add(from.toString()); } if(to != null) { subCommands.add("--to-time"); subCommands.add(to.toString()); } final String rawOutput = execute(subCommands); List<String> rawEvents = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for(String line : rawOutput.split("\n")){ if(line.isEmpty() && sb.length() > 0) { rawEvents.add(sb.toString().trim()); sb = new StringBuilder(); } sb.append(line); sb.append("\n"); } if(sb.length() > 0) { rawEvents.add(sb.toString().trim()); } Iterator<String> iter = rawEvents.iterator(); while (iter.hasNext()) { if(iter.next().isEmpty()) { iter.remove(); } } return rawEvents; } CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL); CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL, TimeZone tz); TimeZone getDefaultTimeZone(); List<String> readAgenda(DateTime from, DateTime to); String createEvent(final String summary, final DateTime from, final DateTime to); }### Answer: @Test public void readAgenda() throws IOException { final DateTime from = DateTime.now().minusDays(1); final DateTime to = from.plusDays(2); List<String> result = toTest.readAgenda(from, to); assertTrue(result.isEmpty()); ArgumentCaptor<CommandLine> cmdCap = ArgumentCaptor.forClass(CommandLine.class); verify(toTest, times(1)).doExecute(cmdCap.capture(), any()); assertEquals("calendar-cli.py", cmdCap.getValue().getExecutable()); assertEquals(15, cmdCap.getValue().getArguments().length); assertEquals("--caldav-url", cmdCap.getValue().getArguments()[0]); assertEquals(CALDAV_URL, cmdCap.getValue().getArguments()[1]); assertEquals("--caldav-user", cmdCap.getValue().getArguments()[2]); assertEquals(CALDAV_USER, cmdCap.getValue().getArguments()[3]); assertEquals("--caldav-pass", cmdCap.getValue().getArguments()[4]); assertEquals(CALDAV_PASSWORD, cmdCap.getValue().getArguments()[5]); assertEquals("--calendar-url", cmdCap.getValue().getArguments()[6]); assertEquals(CALENDAR_URL, cmdCap.getValue().getArguments()[7]); assertEquals("--icalendar", cmdCap.getValue().getArguments()[8]); assertEquals("calendar", cmdCap.getValue().getArguments()[9]); assertEquals("agenda", cmdCap.getValue().getArguments()[10]); assertEquals("--from-time", cmdCap.getValue().getArguments()[11]); assertEquals(from.toString(), cmdCap.getValue().getArguments()[12]); assertEquals("--to-time", cmdCap.getValue().getArguments()[13]); assertEquals(to.toString(), cmdCap.getValue().getArguments()[14]); }
### Question: CalendarCLIAdapter { public String createEvent(final String summary, final DateTime from, final DateTime to) throws IOException { List<String> subCommands = new ArrayList<>(); subCommands.add("calendar"); subCommands.add("add"); final Duration duration = new Interval(from, to).toDuration(); final StringBuilder eventTime = new StringBuilder(); eventTime.append(from.toString("yyyy-MM-dd'T'HH:mm")); eventTime.append("+"); eventTime.append(duration.getStandardMinutes()); eventTime.append("m"); subCommands.add(eventTime.toString()); subCommands.add(summary); final String rawOutput = execute(subCommands); final String uid; final Matcher matcher = eventUUID.matcher(rawOutput); if(matcher.find()) { uid = matcher.group(1); }else{ uid = "<unknown>"; } return uid; } CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL); CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL, TimeZone tz); TimeZone getDefaultTimeZone(); List<String> readAgenda(DateTime from, DateTime to); String createEvent(final String summary, final DateTime from, final DateTime to); }### Answer: @Test public void createEvent() throws IOException { final String summary = "<summary>"; final DateTime from = DateTime.parse("2010-08-13T20:15:00"); final DateTime to = from.plusDays(1).plusHours(1).plusMinutes(1); doAnswer((inv) -> { OutputStream os = (OutputStream)ReflectionTestUtils.getField( ((DefaultExecutor)inv.getArguments()[1]).getStreamHandler(), "out"); os.write("Added event with uid=578ee4a3-3330-11e7-a7d0-0242ac130006\n".getBytes()); return null; }).when(toTest).doExecute(any(), any()); final String result = toTest.createEvent(summary, from, to); assertEquals("578ee4a3-3330-11e7-a7d0-0242ac130006", result); ArgumentCaptor<CommandLine> cmdCap = ArgumentCaptor.forClass(CommandLine.class); verify(toTest, times(1)).doExecute(cmdCap.capture(), any()); assertEquals("--caldav-url", cmdCap.getValue().getArguments()[0]); assertEquals(CALDAV_URL, cmdCap.getValue().getArguments()[1]); assertEquals("--caldav-user", cmdCap.getValue().getArguments()[2]); assertEquals(CALDAV_USER, cmdCap.getValue().getArguments()[3]); assertEquals("--caldav-pass", cmdCap.getValue().getArguments()[4]); assertEquals(CALDAV_PASSWORD, cmdCap.getValue().getArguments()[5]); assertEquals("--calendar-url", cmdCap.getValue().getArguments()[6]); assertEquals(CALENDAR_URL, cmdCap.getValue().getArguments()[7]); assertEquals("calendar", cmdCap.getValue().getArguments()[8]); assertEquals("add", cmdCap.getValue().getArguments()[9]); assertEquals("2010-08-13T20:15+1501m", cmdCap.getValue().getArguments()[10]); assertEquals(summary, cmdCap.getValue().getArguments()[11]); }
### Question: ICalendarParser { public List<VEvent> parseEvents(List<String> rawEvents) { List<VEvent> events = rawEvents.stream() .flatMap(raw -> parseEvent(raw).stream()) .collect(Collectors.toList()); return events; } List<VEvent> parseEvents(List<String> rawEvents); List<VEvent> parseEvent(String rawEvent); }### Answer: @Test public void testParser(){ List<String> rawEvents = Arrays.asList( "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170411T200614Z\n" + "UID:20170411T200614Z-2ce178178dd977ce\n" + "DTSTART;VALUE=DATE:20170527\n" + "DTEND;VALUE=DATE:20170528\n" + "SUMMARY:Great Event!\n" + "STATUS:TENTATIVE\n" + "BEGIN:VALARM\n" + "TRIGGER:-PT420M\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:Great Event!\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR", "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170427T162550Z\n" + "UID:20170427T162550Z-2ce178178dd977ce\n" + "DTSTART:20170524T120000Z\n" + "DTEND:20170524T140000Z\n" + "SUMMARY:Birthdayparteeeeeeeeyyyy\n" + "LOCATION:@Home\n" + "STATUS:TENTATIVE\n" + "BEGIN:VALARM\n" + "TRIGGER:-PT10M\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:Birthdayparteeeeeeeeyyyy\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR", "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170430T163825Z\n" + "UID:20170412T100903Z-2ce178178dd977ce\n" + "SEQUENCE:2\n" + "SUMMARY:Doctor\n" + "DESCRIPTION:Goto doctor right now!\n" + "STATUS:TENTATIVE\n" + "CLASS:PUBLIC\n" + "DTSTART:20170503T080000Z\n" + "DTEND:20170503T090000Z\n" + "BEGIN:VALARM\n" + "TRIGGER:-P1D\n" + "ACTION;X-NC-GROUP-ID=0:DISPLAY\n" + "DESCRIPTION:Doctor\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"); List<VEvent> result = toTest.parseEvents(rawEvents); assertEquals(rawEvents.size(), result.size()); }
### Question: EventMapper { public Event map(VEvent event, TimeZone defaultTimeZone) { Event result = new Event(); nullSave(() -> { final DateTime start = new DateTime(event.getDateStart().getValue().getTime(), DateTimeZone.forTimeZone(defaultTimeZone)); result.setStart(start, event.getDateStart().getValue().hasTime()); }); nullSave(() -> { final DateTime end = new DateTime(event.getDateEnd().getValue().getTime(), DateTimeZone.forTimeZone(defaultTimeZone)); result.setEnd(end, event.getDateStart().getValue().hasTime()); }); nullSave(() -> result.setSummary(event.getSummary().getValue())); nullSave(() -> result.setDescription(event.getDescription().getValue())); return result; } Event map(VEvent event, TimeZone defaultTimeZone); }### Answer: @Test public void map() { final VEvent event = new VEvent(); event.setDateStart(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setDateEnd(DateTime.parse("2010-08-13T20:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setSummary("<summary>"); event.setDescription("<description>"); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertEquals(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getStart().toString()); assertEquals(DateTime.parse("2010-08-13T20:15:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getEnd().toString()); assertEquals("<summary>", result.getSummary()); assertEquals("<description>", result.getDescription()); } @Test public void map_noTime() { final VEvent event = new VEvent(); event.setDateStart(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.UTC).toDate(), false); event.setDateEnd(DateTime.parse("2010-08-13T21:15:00").withZone(DateTimeZone.UTC).toDate(), false); event.setSummary("<summary>"); event.setDescription("<description>"); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertEquals(DateTime.parse("2009-12-15T00:00:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getStart().toString()); assertEquals(DateTime.parse("2010-08-13T00:00:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getEnd().toString()); assertEquals("<summary>", result.getSummary()); assertEquals("<description>", result.getDescription()); } @Test public void map_nullSave() { final VEvent event = new VEvent(); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertNull(result.getStart()); assertNull(result.getEnd()); assertNull(result.getSummary()); assertNull(result.getDescription()); }
### Question: NewEventSpeechlet { private String checkCalendarName(IntentRequest request, Session session) { if(sv(request, SLOT_CALENDAR) == null) { return null; } final String givenName = sv(request, SLOT_CALENDAR); if(givenName == null) { return null; } final String foundName = findCalendarName(givenName); session.setAttribute(SESSION_CALENDAR, foundName); return foundName; } @OnIntent("NewEvent") SpeechletResponse handleDialogAction(final IntentRequest request, final Session session); @OnIntent("SetCalendarInSession") SpeechletResponse handleSetCalendarInSession(IntentRequest request, Session session); static final String SLOT_PREFIX_SUMMARY; static final String SLOT_DATE_FROM; static final String SLOT_TIME_FROM; static final String SLOT_DATE_TO; static final String SLOT_TIME_TO; static final String SLOT_DURATION; static final String SLOT_CALENDAR; static final String SESSION_FROM; static final String SESSION_TO; static final String SESSION_DATE_FORMAT; static final String SESSION_CALENDAR; }### Answer: @Test public void inProgress_CalendarName() throws CalendarWriteException { checkCalendarName("geburtstag", "Geburtstage"); checkCalendarName("geburt", "Geburtstage"); checkCalendarName("termin", "Termine"); checkCalendarName("termine", "Termine"); checkCalendarName("haus", "Haushalt"); checkCalendarName("haushalt", "Haushalt"); checkCalendarName("Progammierung", null); }
### Question: MessageService { public String de(String key, Object...args) { return String.format(messages.getOrDefault(key, key), args); } String de(String key, Object...args); }### Answer: @Test public void de(){ final String messageKey = "help"; final String result = toTest.de(messageKey); assertEquals("Frage mich: was ansteht, um die aktuellen Termine zu erfahren. Oder trage einen neuen Termin ein.", result); }
### Question: SpeechService { public OutputSpeech speechWelcomeMessage(Locale locale) { final String speechText = messageService.de("welcome"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void speechWelcomeMessage(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechWelcomeMessage(aLocale); assertEquals("Willkommen in deinem Kalender.", result.getText()); }
### Question: SpeechService { public OutputSpeech speechHelpMessage(Locale locale) { final String speechText = messageService.de("help"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }### Answer: @Test public void speechHelpMessage(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechHelpMessage(aLocale); assertEquals("Frage mich: was ansteht, um die aktuellen Termine zu erfahren. Oder trage einen neuen Termin ein.", result.getText()); }
### Question: ElementProviderExtension implements IOCExtensionConfigurator { static Collection<String> elemental2ElementTags(final MetaClass type) { final Collection<String> customElementTags = customElementTags(type); if (!customElementTags.isEmpty()) { return customElementTags; } return Elemental2TagMapping.getTags(type.asClass()); } @Override void configure(final IOCProcessingContext context, final InjectionContext injectionContext); @Override void afterInitialization(final IOCProcessingContext context, final InjectionContext injectionContext); }### Answer: @Test public void elemental2ElementTag_customElement() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.class)); assertEquals(singletonList("div"), tags); } @Test public void elemental2ElementTag_customElementChild() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.Child.class)); assertEquals(singletonList("div"), tags); } @Test public void elemental2ElementTag_customElementWithCustomTag() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.WithCustomTag.class)); assertEquals(singletonList("foo"), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChild() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithoutElementAnnotation.class)); assertEquals(emptyList(), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChildWithElementAnnotation() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithoutElementAnnotation.class)); assertEquals(emptyList(), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChildWithCustomTag() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithCustomTag.class)); assertEquals(singletonList("sub-foo"), tags); }
### Question: ErraiAppPropertiesFiles { public static List<URL> getUrls(final ClassLoader... classLoaders) { return Stream.of(classLoaders).flatMap(ErraiAppPropertiesFiles::getUrls).collect(Collectors.toList()); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }### Answer: @Test public void testGetUrls() { final ClassLoader classLoader = ErraiAppPropertiesFilesTest.class.getClassLoader(); final List<URL> urls = ErraiAppPropertiesFiles.getUrls(classLoader); assertEquals(3, urls.size()); }
### Question: ErraiAppPropertiesFiles { public static List<URL> getModulesUrls() { return getModulesUrls(ErraiAppPropertiesFiles.class.getClassLoader()); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }### Answer: @Test public void testGetModuleUrls() { final List<URL> moduleUrls = ErraiAppPropertiesFiles.getModulesUrls(); assertEquals(2, moduleUrls.size()); }
### Question: ErraiAppPropertiesFiles { static String getModuleDir(final URL url) { final String urlString = url.toExternalForm(); final int metaInfEndIndex = urlString.indexOf(META_INF_FILE_NAME); if (metaInfEndIndex > -1) { return urlString.substring(0, metaInfEndIndex); } final int rootDirEndIndex = urlString.indexOf(FILE_NAME); if (rootDirEndIndex > -1) { return urlString.substring(0, rootDirEndIndex); } throw new RuntimeException("URL " + url.toExternalForm() + " is not of a " + FILE_NAME); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }### Answer: @Test public void testGetModuleDirRootFile() throws MalformedURLException { final URL url = new URL("file:/foo/bar/ErraiApp.properties/"); final String moduleDir = ErraiAppPropertiesFiles.getModuleDir(url); assertEquals("file:/foo/bar/", moduleDir); } @Test public void testGetModuleDirMetaInfFile() throws MalformedURLException { final URL url = new URL("file:/foo/bar/META-INF/ErraiApp.properties/"); final String moduleDir = ErraiAppPropertiesFiles.getModuleDir(url); assertEquals("file:/foo/bar/", moduleDir); } @Test(expected = RuntimeException.class) public void testGetModuleDirWithInvalidFileName() throws MalformedURLException { final URL url = new URL("file:/foo/bar/META-INF/InvalidName.properties/"); ErraiAppPropertiesFiles.getModuleDir(url); }
### Question: Elemental2DomUtil { public boolean removeAllElementChildren(final Node node) { final boolean hadChildren = node.lastChild != null; while (node.lastChild != null) { node.removeChild(node.lastChild); } return hadChildren; } boolean removeAllElementChildren(final Node node); void appendWidgetToElement(final HTMLElement parent, final Widget child); HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement); HTMLElement asHTMLElement(final org.jboss.errai.common.client.dom.HTMLElement htmlElement); org.jboss.errai.common.client.dom.HTMLElement asHTMLElement(final HTMLElement htmlElement); }### Answer: @Test public void testRemoveAllElementChildrenWhenNodeDoesNotHaveAnyChildren() { final Node node = Mockito.spy(makeNode()); final boolean hadChildren = elemental2DomUtil.removeAllElementChildren(node); Mockito.verify(node, Mockito.never()).removeChild(any()); assertFalse(hadChildren); } @Test public void testRemoveAllElementChildrenWhenNodeHasChildren() { final Node child1 = mock(Node.class); final Node child2 = mock(Node.class); final Node node = Mockito.spy(makeNode(child1, child2)); final boolean hadChildren = elemental2DomUtil.removeAllElementChildren(node); Mockito.verify(node).removeChild(child1); Mockito.verify(node).removeChild(child2); assertTrue(hadChildren); }
### Question: Elemental2DomUtil { public HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement) { return Js.cast(gwtElement); } boolean removeAllElementChildren(final Node node); void appendWidgetToElement(final HTMLElement parent, final Widget child); HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement); HTMLElement asHTMLElement(final org.jboss.errai.common.client.dom.HTMLElement htmlElement); org.jboss.errai.common.client.dom.HTMLElement asHTMLElement(final HTMLElement htmlElement); }### Answer: @Test public void testAsHTMLElementForGWTElement() throws Exception { final com.google.gwt.dom.client.Element gwtElement = mock(com.google.gwt.dom.client.Element.class); final HTMLElement expectedElement = mock(HTMLElement.class); mockJsCast(expectedElement, gwtElement); final HTMLElement actualElement = elemental2DomUtil.asHTMLElement(gwtElement); assertSame(expectedElement, actualElement); } @Test public void testAsHTMLElementForErraiHTMLElement() throws Exception { final org.jboss.errai.common.client.dom.HTMLElement htmlElement = mock( org.jboss.errai.common.client.dom.HTMLElement.class); final HTMLElement expectedElement = mock(HTMLElement.class); mockJsCast(expectedElement, htmlElement); final HTMLElement actualElement = elemental2DomUtil.asHTMLElement(htmlElement); assertSame(expectedElement, actualElement); } @Test public void testAsHTMLElementForHTMLElement() throws Exception { final org.jboss.errai.common.client.dom.HTMLElement deprecatedElement = mock( org.jboss.errai.common.client.dom.HTMLElement.class); final HTMLElement htmlElement = mock(HTMLElement.class); mockJsCast(deprecatedElement, htmlElement); org.jboss.errai.common.client.dom.HTMLElement actualElement = elemental2DomUtil.asHTMLElement(htmlElement); assertSame(deprecatedElement, actualElement); }
### Question: Reflections extends ReflectionUtils { public <T> Set<Class<? extends T>> getSubTypesOf(final Class<T> type) { Set<String> subTypes = store.getSubTypesOf(type.getName()); return ImmutableSet.copyOf(ReflectionUtils.<T>forNames(subTypes)); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void testSubTypesOf() { assertThat(reflections.getSubTypesOf(I1.class), are(I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat(reflections.getSubTypesOf(I2.class), are(C1.class, C2.class, C3.class, C5.class)); }
### Question: Reflections extends ReflectionUtils { public Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation) { Set<String> typesAnnotatedWith = store.getTypesAnnotatedWith(annotation.getName()); return ImmutableSet.copyOf(forNames(typesAnnotatedWith)); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void testTypesAnnotatedWith() { assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(MAI1.class), are(AI1.class)); assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(AI2.class), are(I2.class)); assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(AC1.class), are(C1.class, C2.class, C3.class, C5.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(AI1.class, false), are(I1.class, I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(AI2.class, false), are(I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat(reflections.getTypesAnnotatedWith(AM1.class), isEmpty); AC2 ac2 = new AC2() { public String value() { return "ugh?!"; } public Class<? extends Annotation> annotationType() { return AC2.class; } }; assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(ac2), are(C3.class, I3.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(ac2, false), are(C3.class, C5.class, I3.class, C6.class)); }
### Question: Reflections extends ReflectionUtils { public Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation) { Set<String> annotatedWith = store.getMethodsAnnotatedWith(annotation.getName()); Set<Method> result = Sets.newHashSet(); for (String annotated : annotatedWith) { result.add(Utils.getMethodFromDescriptor(annotated)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void testMethodsAnnotatedWith() { try { assertThat(reflections.getMethodsAnnotatedWith(AM1.class), are(C4.class.getDeclaredMethod("m1"), C4.class.getDeclaredMethod("m1", int.class, String[].class), C4.class.getDeclaredMethod("m1", int[][].class, String[][].class), C4.class.getDeclaredMethod("m3"))); AM1 am1 = new AM1() { public String value() { return "1"; } public Class<? extends Annotation> annotationType() { return AM1.class; } }; assertThat(reflections.getMethodsAnnotatedWith(am1), are(C4.class.getDeclaredMethod("m1"), C4.class.getDeclaredMethod("m1", int.class, String[].class), C4.class.getDeclaredMethod("m1", int[][].class, String[][].class))); } catch (NoSuchMethodException e) { fail(); } }
### Question: Reflections extends ReflectionUtils { public Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation) { final Set<Field> result = Sets.newHashSet(); Collection<String> annotatedWith = store.getFieldsAnnotatedWith(annotation.getName()); for (String annotated : annotatedWith) { result.add(Utils.getFieldFromString(annotated)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void testFieldsAnnotatedWith() { try { assertThat(reflections.getFieldsAnnotatedWith(AF1.class), are(C4.class.getDeclaredField("f1"), C4.class.getDeclaredField("f2") )); assertThat(reflections.getFieldsAnnotatedWith(new AF1() { public String value() { return "2"; } public Class<? extends Annotation> annotationType() { return AF1.class; } }), are(C4.class.getDeclaredField("f2"))); } catch (NoSuchFieldException e) { fail(); } }
### Question: Reflections extends ReflectionUtils { public Set<Method> getConverters(final Class<?> from, final Class<?> to) { Set<Method> result = Sets.newHashSet(); Set<String> converters = store.getConverters(from.getName(), to.getName()); for (String converter : converters) { result.add(Utils.getMethodFromDescriptor(converter)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void testConverters() { try { assertThat(reflections.getConverters(C2.class, C3.class), are(C4.class.getDeclaredMethod("c2toC3", C2.class))); } catch (NoSuchMethodException e) { fail(); } }
### Question: Reflections extends ReflectionUtils { public static Reflections collect() { return new Reflections(new ConfigurationBuilder()). collect("META-INF/reflections", new FilterBuilder().include(".*-reflections.xml")); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }### Answer: @Test public void collect() { String path = getUserDir() + "/target/test-classes" + "/META-INF/reflections/testModel-reflections.xml"; try { Predicate<String> filter = new FilterBuilder().include("org.jboss.errai.reflections.TestModel\\$.*"); Reflections testModelReflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners( new SubTypesScanner().filterResultsBy(filter), new TypeAnnotationsScanner().filterResultsBy(filter)) .setUrls(asList(ClasspathHelper.forClass(TestModel.class)))); testModelReflections.scan(); testModelReflections.save(path); reflections = Reflections.collect(); reflections.scan(); testAll(); } finally { new File(path).delete(); } }
### Question: KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public boolean isLoggedIn() { return keycloakIsLoggedIn() || wrappedAuthService.isLoggedIn(); } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }### Answer: @Test public void isLoggedInReturnsFalseWhenNoUserLoggedIn() throws Exception { assertFalse(authService.isLoggedIn()); }
### Question: KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public User getUser() { if (keycloakIsLoggedIn()) { return getKeycloakUser(); } else if (wrappedAuthService.isLoggedIn()) { return wrappedAuthService.getUser(); } else { return User.ANONYMOUS; } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }### Answer: @Test public void getUserReturnsAnonymousWhenNoUserLoggedIn() throws Exception { assertEquals(User.ANONYMOUS, authService.getUser()); }
### Question: KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public void logout() { if (keycloakIsLoggedIn()) { keycloakLogout(); try { if (RpcContext.getMessage() != null) ((HttpServletRequest) RpcContext.getServletRequest()).logout(); } catch (ServletException e) { throw new AuthenticationException("An error occurred while attempting to log out of Keycloak."); } } else if (wrappedAuthService.isLoggedIn()) { wrappedAuthService.logout(); } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }### Answer: @Test public void logoutIsIdempotent() throws Exception { authService.logout(); authService.logout(); isLoggedInReturnsFalseWhenNoUserLoggedIn(); }
### Question: KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public User login(final String username, final String password) { if (!keycloakIsLoggedIn()) { return wrappedAuthService.login(username, password); } else { throw new AlreadyLoggedInException("Already logged in through Keycloak."); } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }### Answer: @Test(expected = AlreadyLoggedInException.class) public void loginFailsIfKeycloakUserLoggedIn() throws Exception { getUserReturnsUserWhenKeycloakUserLoggedIn(); authService.login(PREFERRED_USERNAME, ""); }
### Question: KeycloakAuthenticationService implements AuthenticationService, Serializable { void setSecurityContext(final KeycloakSecurityContext keycloakSecurityContext) { if (wrappedAuthService.isLoggedIn() && keycloakSecurityContext != null) { throw new AlreadyLoggedInException("Logged in as " + wrappedAuthService.getUser()); } this.keycloakSecurityContext = keycloakSecurityContext; keycloakUser = null; } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }### Answer: @Test(expected = AlreadyLoggedInException.class) public void settingKeycloakUserFailsIfWrappedUserLoggedIn() throws Exception { getUserReturnsUserWhenWrappedUserLoggedIn(); authService.setSecurityContext(securityContext); }
### Question: UserHostPageFilter implements Filter { String securityContextJson(final User user) { final String userJson = ServerMarshalling.toJSON(user); return "{\"" + SecurityConstants.DICTIONARY_USER + "\": " + userJson + "}"; } @Override void init(FilterConfig filterConfig); @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); }### Answer: @Test public void testSecurityContextJsonWhenAGroupHasAnApostrophe() throws Exception { final UserImpl user = new UserImpl("Mary", roles("admin"), groups("girls'", "programmer", "admin")); final String json = filter.securityContextJson(user); assertTrue(isValid(json)); } @Test public void testSecurityContextJsonWhenAGroupHasAQuote() throws Exception { final UserImpl user = new UserImpl("Mary", roles("admin"), groups("girls\"", "programmer", "admin")); final String json = filter.securityContextJson(user); assertTrue(isValid(json)); }
### Question: EventDispatcher implements MessageCallback { static String getConversationalSessionId(Class<? extends Object> eventType) { final QueueSession queueSession = RpcContext.getQueueSession(); if (eventType.isAnnotationPresent(Conversational.class) && queueSession != null && queueSession.getSessionId() != null) { return queueSession.getSessionId(); } return null; } EventDispatcher(final BeanManager beanManager, final EventRoutingTable eventRoutingTable, final MessageBus messageBus, final Set<String> observedEvents, final Map<String, Annotation> eventQualifiers); @Override @SuppressWarnings("unchecked") void callback(final Message message); boolean isRoutable(final LocalContext localContext, final Message message); void sendEventToClients(Object event, EventMetadata emd); }### Answer: @Test public void conversationalEventWithContext() { RpcContext.set(new MockMessage()); final String convSessionId = EventDispatcher.getConversationalSessionId(MyConversationalEvent.class); assertEquals("bearista", convSessionId); } @Test public void conversationalEventWithoutContext() { final String convSessionId = EventDispatcher.getConversationalSessionId(MyConversationalEvent.class); assertNull(convSessionId); } @Test public void nonConversationalEventWithContext() { RpcContext.set(new MockMessage()); final String convSessionId = EventDispatcher.getConversationalSessionId(MyNonConversationalEvent.class); assertNull(convSessionId); } @Test public void nonConversationalEventWithoutContext() { final String convSessionId = EventDispatcher.getConversationalSessionId(MyNonConversationalEvent.class); assertNull(convSessionId); }
### Question: Elemental2TagMapping { static Collection<String> getTags(final Class<?> elemental2ElementClass) { if (elemental2ElementClass == null || Element.class.equals(elemental2ElementClass)) { return Collections.emptyList(); } final Collection<String> tags = TAG_NAMES_BY_DOM_INTERFACE.get(elemental2ElementClass); if (tags.isEmpty()) { return getTags(elemental2ElementClass.getSuperclass()); } return tags; } }### Answer: @Test public void testGetTags() { assertEquals("null should return no tag", emptyList(), getTags(null)); assertEquals("Object.class should not have any mapped tag name", emptyList(), getTags(Object.class)); assertEquals("String.class should not have any mapped tag name", emptyList(), getTags(String.class)); assertEquals("HTMLDivElement should have a tag mapped to it", singletonList("div"), getTags(HTMLDivElement.class)); assertEquals("HTMLDivElement subclass should have a tag mapped to it", singletonList("div"), getTags(CustomElement.class)); assertEquals("HTMLDivElement subclass should have a tag mapped to it", singletonList("div"), getTags(CustomElement.Child.class)); }
### Question: TemplatedCodeDecorator extends IOCDecoratorExtension<Templated> { @Override public void generateDecorator(final Decorable decorable, final FactoryController controller) { final MetaClass declaringClass = decorable.getDecorableDeclaringType(); final Templated anno = (Templated) decorable.getAnnotation(); final Class<?> templateProvider = anno.provider(); final boolean customProvider = templateProvider != Templated.DEFAULT_PROVIDER.class; final Optional<String> styleSheetPath = getTemplateStyleSheetPath(declaringClass); final boolean explicitStyleSheetPresent = styleSheetPath.filter(path -> Thread.currentThread().getContextClassLoader().getResource(path) != null).isPresent(); if (declaringClass.isAssignableTo(Composite.class)) { logger.warn("The @Templated class, {}, extends Composite. This will not be supported in future versions.", declaringClass.getFullyQualifiedName()); } if (styleSheetPath.isPresent() && !explicitStyleSheetPresent) { throw new GenerationException("@Templated class [" + declaringClass.getFullyQualifiedName() + "] declared a stylesheet [" + styleSheetPath + "] that could not be found."); } final List<Statement> initStmts = new ArrayList<>(); generateTemplatedInitialization(decorable, controller, initStmts, customProvider); if (customProvider) { final Statement init = Stmt.invokeStatic(TemplateUtil.class, "provideTemplate", templateProvider, getTemplateUrl(declaringClass), Stmt.newObject(TemplateRenderingCallback.class) .extend() .publicOverridesMethod("renderTemplate", Parameter.of(String.class, "template", true)) .appendAll(initStmts) .finish() .finish()); controller.addInitializationStatements(Collections.singletonList(init)); } else { controller.addInitializationStatements(initStmts); } controller.addDestructionStatements(generateTemplateDestruction(decorable)); controller.addInitializationStatementsToEnd(Collections.<Statement>singletonList(invokeStatic(StyleBindingsRegistry.class, "get") .invoke("updateStyles", Refs.get("instance")))); } TemplatedCodeDecorator(final Class<Templated> decoratesWith); @Override void generateDecorator(final Decorable decorable, final FactoryController controller); static Optional<String> getTemplateStyleSheetPath(final MetaClass type); static String getTemplateFileName(final MetaClass type); static String getTemplateUrl(final MetaClass type); static String getTemplateFragmentName(final MetaClass type); }### Answer: @Test public void nativeQuickHandlerWithNoEventTypeThrowsGenerationException() throws Exception { final MetaMethod handlerMethod = mock(MetaMethod.class); final MetaParameter eventParam = mock(MetaParameter.class); when(templatedClass.getMethodsAnnotatedWith(EventHandler.class)) .thenReturn(singletonList(handlerMethod)); when(handlerMethod.getAnnotation(EventHandler.class)).thenReturn(defaultHandlerAnno); when(handlerMethod.getParameters()).thenReturn(new MetaParameter[] { eventParam }); when(eventParam.getType()).thenReturn(elemental2EventClass); try { decorator.generateDecorator(decorable, controller); fail("No error was observed."); } catch (final GenerationException observed) { try { assertTrue("Error must mention @ForEvent", ofNullable(observed.getMessage()).filter(m -> m.contains("@ForEvent")).isPresent()); assertTrue("Error must mention @BrowserEvent", ofNullable(observed.getMessage()).filter(m -> m.contains("@BrowserEvent")).isPresent()); } catch (final AssertionError ae) { ae.initCause(observed); throw ae; } } catch (final AssertionError ae) { throw ae; } catch (final Throwable t) { throw new AssertionError("Unexpected error: " + t.getMessage(), t); } }
### Question: TranslationServiceGenerator extends AbstractAsyncGenerator { public static String getLocaleFromBundlePath(final String bundlePath) { final Matcher matcher = LOCALE_IN_FILENAME_PATTERN.matcher(bundlePath); if (matcher != null && matcher.matches()) { final StringBuilder locale = new StringBuilder(); final String lang = matcher.group(2); if (lang != null) locale.append(lang); final String region = matcher.group(3); if (region != null) locale.append("_").append(region.substring(1)); return locale.toString(); } else { return null; } } @Override String generate(final TreeLogger logger, final GeneratorContext context, final String typeName); @Override String generate(final TreeLogger logger, final GeneratorContext context); static String getLocaleFromBundlePath(final String bundlePath); }### Answer: @Test public void testGetLocaleFromBundleFilename() { Assert.assertEquals(null, TranslationServiceGenerator.getLocaleFromBundlePath("myBundle.json")); Assert.assertEquals(null, TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_US.other")); Assert.assertEquals("en_US", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_US.json")); Assert.assertEquals("en_GB", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en_GB.json")); Assert.assertEquals("en", TranslationServiceGenerator.getLocaleFromBundlePath("myBundle_en.json")); Assert.assertEquals("fr_CA", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr_CA.json")); Assert.assertEquals("fr_FR", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr_FR.json")); Assert.assertEquals("fr", TranslationServiceGenerator.getLocaleFromBundlePath("Some-Other-Bundle_fr.json")); Assert.assertEquals("en_US", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en_US.json")); Assert.assertEquals("en_GB", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en_GB.json")); Assert.assertEquals("en", TranslationServiceGenerator .getLocaleFromBundlePath("org/example/ui/client/local/myBundle_en.json")); }
### Question: TranslationServiceGenerator extends AbstractAsyncGenerator { @SuppressWarnings({ "rawtypes", "unchecked" }) protected static Set<String> recordBundleKeys(final Map<String, Set<String>> discoveredI18nMap, final String locale, final String bundlePath) { InputStream is = null; final Set<String> duplicates = new HashSet<>(); try { final Set<String> keys = discoveredI18nMap.computeIfAbsent(locale, l -> new HashSet<>()); is = TranslationServiceGenerator.class.getClassLoader().getResourceAsStream(bundlePath); if (isJsonBundle(bundlePath)) { final JsonFactory jsonFactory = new JsonFactory(); final JsonParser jp = jsonFactory.createJsonParser(is); JsonToken token = jp.nextToken(); while (token != null) { token = jp.nextToken(); if (token == JsonToken.FIELD_NAME) { final String name = jp.getCurrentName(); if (keys.contains(name)) { duplicates.add(name); } keys.add(name); } } } else { final Properties properties = new Properties(); properties.load(is); final Set<String> propertFileKeys = (Set) properties.keySet(); propertFileKeys .stream() .filter(key -> keys.contains(key)) .collect(Collectors.toCollection(() -> duplicates)); keys.addAll(propertFileKeys); } } catch (final Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(is); } return duplicates; } @Override String generate(final TreeLogger logger, final GeneratorContext context, final String typeName); @Override String generate(final TreeLogger logger, final GeneratorContext context); static String getLocaleFromBundlePath(final String bundlePath); }### Answer: @Test public void testRecordBundleKeys() { String jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest.json"; Map<String, Set<String>> result = new HashMap<String, Set<String>>(); TranslationServiceGenerator.recordBundleKeys(result, null, jsonResourcePath); Assert.assertEquals(1, result.keySet().size()); Set<String> defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest_fr_FR.json"; TranslationServiceGenerator.recordBundleKeys(result, "fr_FR", jsonResourcePath); Assert.assertEquals(2, result.keySet().size()); defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); Set<String> fr_FR_Keys = result.get("fr_FR"); Assert.assertEquals(10, fr_FR_Keys.size()); jsonResourcePath = "org/jboss/errai/ui/test/i18n/client/I18nTemplateTest_da.json"; TranslationServiceGenerator.recordBundleKeys(result, "da", jsonResourcePath); Assert.assertEquals(3, result.keySet().size()); defaultKeys = result.get(null); Assert.assertEquals(11, defaultKeys.size()); fr_FR_Keys = result.get("fr_FR"); Assert.assertEquals(10, fr_FR_Keys.size()); Set<String> da_Keys = result.get("da"); Assert.assertEquals(9, da_Keys.size()); }
### Question: MetricGetter { @SafeVarargs public static final TagValue[][] getTagCombinations(Class<? extends TagValue>... tagValueClazzes) { int combinations = 1; for (Class<? extends TagValue> clazz : tagValueClazzes) { combinations *= clazz.getEnumConstants().length; } TagValue[][] result = new TagValue[combinations][]; List<List<TagValue>> tagLists = getTagCombinations(Arrays.asList(tagValueClazzes)); for (int i = 0; i < tagLists.size(); i++) { List<TagValue> tagList = tagLists.get(i); result[i] = tagList.toArray(new TagValue[tagList.size()]); } return result; } MetricGetter(Class<?> clazz, String methodName); CounterMetric getInvocations(InvocationResult result, InvocationFallback fallbackUsed); CounterMetric getRetryCalls(RetryRetried retried, RetryResult result); CounterMetric getRetryRetries(); CounterMetric getTimeoutCalls(TimeoutTimedOut timedOut); Optional<Histogram> getTimeoutExecutionDuration(); CounterMetric getCircuitBreakerCalls(CircuitBreakerResult cbResult); CounterMetric getCircuitBreakerOpened(); GaugeMetric getCircuitBreakerState(CircuitBreakerState cbState); CounterMetric getBulkheadCalls(BulkheadResult bulkheadResult); GaugeMetric getBulkheadExecutionsRunning(); GaugeMetric getBulkheadExecutionsWaiting(); Optional<Histogram> getBulkheadRunningDuration(); Optional<Histogram> getBulkheadWaitingDuration(); void baselineMetrics(); @SafeVarargs static final TagValue[][] getTagCombinations(Class<? extends TagValue>... tagValueClazzes); }### Answer: @Test public void testTagComboZero() { TagValue[][] expected = {{}}; assertEquals(MetricGetter.getTagCombinations(), expected); } @Test public void testTagComboOne() { TagValue[][] expected = {{TimeoutTimedOut.TRUE}, {TimeoutTimedOut.FALSE}}; assertEquals(MetricGetter.getTagCombinations(TimeoutTimedOut.class), expected); } @Test public void testTagComboTwo() { TagValue[][] expected = {{TimeoutTimedOut.TRUE, InvocationResult.VALUE_RETURNED}, {TimeoutTimedOut.TRUE, InvocationResult.EXCEPTION_THROWN}, {TimeoutTimedOut.FALSE, InvocationResult.VALUE_RETURNED}, {TimeoutTimedOut.FALSE, InvocationResult.EXCEPTION_THROWN}}; assertEquals(MetricGetter.getTagCombinations(TimeoutTimedOut.class, InvocationResult.class), expected); }
### Question: Sleeper { public void sleepWhileConditionMet(BooleanSupplier condition, Time duration) throws InterruptedException { long timeoutMs = duration.valueAsMillis(); long sleepingPeriodMs = getSleepingPeriodMs(timeoutMs); long timeWaited = 0; while (condition.getAsBoolean() && timeWaited < timeoutMs) { sleepMs(sleepingPeriodMs); timeWaited += sleepingPeriodMs; } } void sleep(Time duration); void sleepWhileConditionMet(BooleanSupplier condition, Time duration); }### Answer: @Test public void sleepWhileConditionMet_conditionDoesNotChangeBeforeTime_sleepsAllottedTime() throws Exception { final long SLEEP_TIME_MS = 100; Sleeper sleeper = new Sleeper(); long start = System.nanoTime(); sleeper.sleepWhileConditionMet(Suppliers.of(true), Time.milliseconds(SLEEP_TIME_MS)); long passed = (long) ((System.nanoTime() - start) * 1e-6); long difference = Math.abs(passed - SLEEP_TIME_MS); assertThat(difference, lessThanOrEqualTo(SLEEP_TIME_MS / 5)); }
### Question: RequirementsControl { public Optional<Action> getActionOnRequirement(Requirement requirement) { return Optional.ofNullable(mActionsOnRequirement.get(requirement)); } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }### Answer: @Test public void getActionOnSubsystem_subsystemHasNoAction_returnsEmpty() throws Exception { Subsystem subsystem = mock(Subsystem.class); Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem); assertFalse(optionalAction.isPresent()); } @Test public void getActionOnSubsystem_forSubsystemWithAction_returnsAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mActionsOnSubsystems.put(subsystem, action); Optional<Action> optionalAction = mRequirementsControl.getActionOnRequirement(subsystem); assertThat(optionalAction.get(), equalTo(action)); }
### Question: RequirementsControl { public void setDefaultActionOnSubsystem(Subsystem subsystem, Action action) { if (!action.getConfiguration().getRequirements().contains(subsystem)) { action.configure() .requires(subsystem) .save(); } mDefaultActionsOnSubsystems.put(subsystem, action); } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }### Answer: @Test public void setDefaultActionOnSubsystem_defaultAlreadyExists_replacesAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mDefaultActionsOnSubsystems.put(subsystem, action); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction)); } @Test public void setDefaultActionOnSubsystem_defaultNotExists_putAction() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action newAction = ActionsMock.actionMocker() .mockWithRequirements(Collections.singleton(subsystem)) .build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(mDefaultActionsOnSubsystems, IsMapContaining.hasEntry(subsystem, newAction)); } @Test public void setDefaultActionOnSubsystem_subsystemNotInRequirements_subsystemAdded() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action newAction = ActionsMock.actionMocker().build(); mRequirementsControl.setDefaultActionOnSubsystem(subsystem, newAction); MatcherAssert.assertThat(newAction.getConfiguration().getRequirements(), IsIterableContaining.hasItem(subsystem)); }
### Question: RequirementsControl { public Map<Subsystem, Action> getDefaultActionsToStart() { Map<Subsystem, Action> actionsToStart = new HashMap<>(); for (Map.Entry<Subsystem, Action> entry : mDefaultActionsOnSubsystems.entrySet()) { if (mActionsOnRequirement.containsKey(entry.getKey())) { continue; } actionsToStart.put(entry.getKey(), entry.getValue()); } return actionsToStart; } RequirementsControl(Logger logger, Map<Requirement, Action> actionsOnRequirement, Map<Subsystem, Action> defaultActionsOnSubsystems); RequirementsControl(Logger logger); void updateRequirementsNoCurrentAction(Action action); void updateRequirementsWithNewRunningAction(Action action); Optional<Action> getActionOnRequirement(Requirement requirement); void setDefaultActionOnSubsystem(Subsystem subsystem, Action action); Map<Subsystem, Action> getDefaultActionsToStart(); }### Answer: @Test public void getDefaultActionsToStart_noActionsAreRunning_returnsAll() throws Exception { Map<Subsystem, Action> defaultActions = new HashMap<>(); defaultActions.put(mock(Subsystem.class), mock(Action.class)); defaultActions.put(mock(Subsystem.class), mock(Action.class)); mDefaultActionsOnSubsystems.putAll(defaultActions); Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart(); MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(defaultActions.size())); defaultActions.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a))); } @Test public void getDefaultActionsToStart_someActionsRunning_returnsTheOnesNotRunning() throws Exception { Map<Subsystem, Action> notRunning = new HashMap<>(); notRunning.put(mock(Subsystem.class), mock(Action.class)); notRunning.put(mock(Subsystem.class), mock(Action.class)); Map<Subsystem, Action> running = new HashMap<>(); running.put(mock(Subsystem.class), mock(Action.class)); running.put(mock(Subsystem.class), mock(Action.class)); mDefaultActionsOnSubsystems.putAll(notRunning); mDefaultActionsOnSubsystems.putAll(running); mActionsOnSubsystems.putAll(running); Map<Subsystem, Action> defaultActionsToStart = mRequirementsControl.getDefaultActionsToStart(); MatcherAssert.assertThat(defaultActionsToStart, IsMapWithSize.aMapWithSize(notRunning.size())); notRunning.forEach((s, a) -> MatcherAssert.assertThat(defaultActionsToStart, IsMapContaining.hasEntry(s, a))); }
### Question: ActionControl { public void startAction(Action action) { if (mRunningActions.containsKey(action)) { throw new IllegalStateException("action already running"); } if (mNextRunActions.contains(action)) { throw new IllegalStateException("action already scheduled to run"); } mNextRunActions.add(action); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void startAction_actionNotRunning_addsToRunning() throws Exception { Action action = mock(Action.class); mActionControl.startAction(action); assertThat(mNextRunActions, IsIterableContaining.hasItem(action)); } @Test public void startAction_actionRunning_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mRunningActions.put(action, mock(ActionContext.class)); mActionControl.startAction(action); }); } @Test public void startAction_actionRunForNext_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mNextRunActions.add(action); mActionControl.startAction(action); }); }
### Question: ActionControl { public void cancelAction(Action action) { ActionContext context = mRunningActions.get(action); if (context != null) { context.cancelAction(); } else { throw new IllegalStateException("action is not running"); } } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void cancelAction_actionRunning_cancels() throws Exception { Action action = mock(Action.class); ActionContext context = mock(ActionContext.class); mRunningActions.put(action, context); mActionControl.cancelAction(action); verify(context, times(1)).cancelAction(); } @Test public void cancelAction_actionNotRunning_throwsIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, ()-> { Action action = mock(Action.class); mActionControl.cancelAction(action); }); }
### Question: Time implements Comparable<Time> { public boolean before(Time other) { return lessThan(other); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }### Answer: @Test public void before_thisIsNotValidOtherIsNotValid_returnsFalse() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertFalse(THIS.before(OTHER)); }
### Question: ActionControl { public boolean isActionRunning(Action action) { return mRunningActions.containsKey(action); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void isRunning_actionNotRunning_returnsFalse() throws Exception { Action action = mock(Action.class); Assertions.assertFalse(mActionControl.isActionRunning(action)); } @Test public void isRunning_actionRunning_returnsTrue() throws Exception { Action action = mock(Action.class); mRunningActions.put(action, mock(ActionContext.class)); Assertions.assertTrue(mActionControl.isActionRunning(action)); }
### Question: ActionControl { public void updateActionsForNextRun(Iterable<Action> actionsToRemove) { actionsToRemove.forEach(this::internalRemove); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void updateActionsForNextRun_withActionsToRemove_runMarkedFinished() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.updateActionsForNextRun(actions.keySet()); actions.values().forEach((ctx)-> verify(ctx, times(1)).runFinished()); } @Test public void updateActionsForNextRun_withActionsToRemove_requirementsMarkedNoAction() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.updateActionsForNextRun(actions.keySet()); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsNoCurrentAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.keySet().toArray())); }
### Question: ActionControl { public void startNewActions() { mNextRunActions.forEach(this::internalAdd); mNextRunActions.clear(); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void startNewActions_withActionsToStart_startsActions() throws Exception { Collection<Action> actions = Arrays.asList( ActionsMock.actionMocker().build(), ActionsMock.actionMocker().build() ); mNextRunActions.addAll(actions); mActionControl.startNewActions(); MatcherAssert.assertThat(mRunningActions.keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.toArray())); } @Test public void startNewActions_withActionsToStart_updatesRequirements() throws Exception { Collection<Action> actions = Arrays.asList( ActionsMock.actionMocker().build(), ActionsMock.actionMocker().build() ); mNextRunActions.addAll(actions); mActionControl.startNewActions(); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsWithNewRunningAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.toArray())); }
### Question: ActionControl { public void cancelAllActions() { mNextRunActions.clear(); mRunningActions.forEach(this::onInternalRemove); mRunningActions.clear(); } ActionControl(Clock clock, RequirementsControl requirementsControl, Map<Action, ActionContext> runningActions, Collection<Action> nextRunActions); ActionControl(Clock clock, RequirementsControl requirementsControl); Set<Map.Entry<Action, ActionContext>> getRunningActionContexts(); void startAction(Action action); void cancelAction(Action action); boolean isActionRunning(Action action); void startNewActions(); void updateActionsForNextRun(Iterable<Action> actionsToRemove); void cancelActionsIf(Predicate<? super Action> predicate); void cancelAllActions(); }### Answer: @Test public void stopAllActions_withRunningActions_runMarkedFinished() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.cancelAllActions(); actions.values().forEach((ctx)-> verify(ctx, times(1)).runFinished()); } @Test public void stopAllActions_withRunningActions_requirementsMarkedNoAction() throws Exception { Map<Action, ActionContext> actions = new HashMap<>(); actions.put(mock(Action.class), mock(ActionContext.class)); actions.put(mock(Action.class), mock(ActionContext.class)); mRunningActions.putAll(actions); mActionControl.cancelAllActions(); ArgumentCaptor<Action> captor = ArgumentCaptor.forClass(Action.class); verify(mRequirementsControl, times(actions.size())).updateRequirementsNoCurrentAction(captor.capture()); MatcherAssert.assertThat(captor.getAllValues(), IsIterableContainingInAnyOrder.containsInAnyOrder(actions.keySet().toArray())); }
### Question: SchedulerIteration { public void run(SchedulerMode mode) { mActionsToRemove.clear(); startNewActions(); runActions(mode); startDefaultSubsystemActions(mode); readyForNextRun(); } SchedulerIteration(ActionControl actionControl, RequirementsControl requirementsControl, Logger logger); void run(SchedulerMode mode); }### Answer: @Test public void run_withActions_runsActions() throws Exception { ActionContext actionContext = ActionsMock.contextMocker() .runFinished(false) .build(); mActionControlMock.runningAction(actionContext); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(actionContext, times(1)).run(); } @Test public void run_subsystemsWithDefaults_startsDefaultActions() throws Exception { Subsystem subsystem = mock(Subsystem.class); Action action = mock(Action.class); mSubsystemControlMock.setDefaultAction(subsystem, action); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(action, times(1)).start(); } @Test public void run_actionsIsFinished_removesAction() throws Exception { ActionContext actionContext = ActionsMock.contextMocker() .runFinished(true) .build(); Action action = mActionControlMock.runningAction(actionContext); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); mActionControlMock.verify(times(1)).updateActionsForNextRun(argThat(IsIterableContaining.hasItems(action))); } @Test public void run_disabledMode_removesActionsNotAllowedInDisabled() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); mActionControlMock.runningAction(action); mSchedulerIteration.run(SchedulerModeMock.mockDisabledMode()); mActionControlMock.verify(times(1)).updateActionsForNextRun(argThat(IsIterableContaining.hasItems(action))); } @Test public void run_disabledMode_doesNotRunNotAllowedInDisabled() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.runningAction(action); mSchedulerIteration.run(SchedulerModeMock.mockDisabledMode()); verify(actionContext, never()).run(); } @Test public void run_userExceptionFromAction_cancelsAction() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.runningAction(action); when(actionContext.run()).thenThrow(new RuntimeException()); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(action, times(1)).cancel(); } @Test public void run_newActionsReady_startsThem() throws Exception { Action action = ActionsMock.actionMocker() .mockRunWhenDisabled(false) .build(); ActionContext actionContext = mActionControlMock.pendingAction(action); mSchedulerIteration.run(SchedulerModeMock.mockNotDisabledMode()); verify(actionContext, times(1)).run(); }
### Question: Time implements Comparable<Time> { public boolean after(Time other) { return largerThan(other); } Time(long value, TimeUnit unit); static Time of(long value, TimeUnit unit); static Time milliseconds(long valueMs); static Time seconds(long valueSeconds); static Time seconds(double valueSeconds); static Time minutes(long valueMinutes); static Time minutes(double valueMinutes); long value(); TimeUnit unit(); Time toUnit(TimeUnit newTimeUnit); long valueAsMillis(); double valueAsSeconds(); boolean isValid(); Time add(Time other); Time sub(Time other); boolean before(Time other); boolean lessThan(Time other); boolean lessThanOrEquals(Time other); boolean after(Time other); boolean largerThan(Time other); boolean largerThanOrEquals(Time other); boolean equals(Time other); @Override int compareTo(Time other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Time earliest(Time... times); static Time latest(Time... times); static final long INVALID_VALUE; static final Time INVALID; }### Answer: @Test public void after_thisIsNotValidOtherIsNotValid_returnsFalse() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertFalse(THIS.after(OTHER)); }