src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
IsoTypeReader { public static float readFixedPoint88(ByteBuffer bb) { byte[] bytes = new byte[2]; bb.get(bytes); short result = 0; result |= ((bytes[0] << 8) & 0xFF00); result |= ((bytes[1]) & 0xFF); return ((float) result) / 256; } static long readUInt32BE(ByteBuffer bb); static long readUInt32(ByteBuffer bb); static... | @Test public void testFixedPoint88() throws IOException { final double fixedPointTest1 = 10.13; final double fixedPointTest2 = -10.13; ByteBuffer bb = ByteBuffer.allocate(4); IsoTypeWriter.writeFixedPoint88(bb, fixedPointTest1); IsoTypeWriter.writeFixedPoint88(bb, fixedPointTest2); bb.rewind(); Assert.assertEquals("fix... |
IsoTypeReader { public static String read4cc(ByteBuffer bb) { bb.get(codeBytes); int result = ((codeBytes[0] << 24) & 0xFF000000); result |= ((codeBytes[1] << 16) & 0xFF0000); result |= ((codeBytes[2] << 8) & 0xFF00); result |= ((codeBytes[3]) & 0xFF); String code; if ((code = (String) codeCache.get(result)) != null) {... | @Test public void testRead4cc() throws IOException { ByteBuffer bb = ByteBuffer.wrap("abcd".getBytes()); String code = IsoTypeReader.read4cc(bb); Assert.assertEquals(4, bb.position()); Assert.assertEquals("abcd", code); } |
BitWriterBuffer { public void writeBits(int i, int numBits) { assert i <= ((1 << numBits)-1): String.format("Trying to write a value bigger (%s) than the number bits (%s) allows. " + "Please mask the value before writing it and make your code is really working as intended.", i, (1<<numBits)-1); int left = 8 - position ... | @Test public void testWriteWithinBuffer() { ByteBuffer b = ByteBuffer.allocate(2); b.put((byte) 0); BitWriterBuffer bwb = new BitWriterBuffer(b); bwb.writeBits(15, 4); Assert.assertEquals("0000000011110000", toString(b)); }
@Test public void testSimple() { ByteBuffer bb = ByteBuffer.allocate(4); BitWriterBuffer bitWrit... |
BindController { @RequestMapping(value = "/baseType") public String baseType(@RequestParam("age") int age) { return "age:" + age; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") ... | @Test public void baseType() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("age", "20"); String response = mockMvc.perform(get("/baseType") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsStri... |
BindController { @RequestMapping(value = "date2") public String date2(Date date2) { return Objects.nonNull(date2) ? date2.toString() : "绑定date2参数失败,date2为null"; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @Re... | @Test public void date2() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("date2", "2020-03-14"); String response = mockMvc.perform(get("/date2") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAs... |
BindController { @GetMapping(value = "/book") public String book(HttpServletRequest request) { String contentType = request.getContentType(); if (contentType == null) { return "book.default"; } String typeTxt = "zccoder/txt"; if (typeTxt.equalsIgnoreCase(contentType)) { return "book.txt"; } String typeHtml = "zccoder/h... | @Test public void book() throws Exception { String contentType = "zccoder/txt"; String response = mockMvc.perform(get("/book") .contentType(contentType)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
BindController { @GetMapping(value = "/subject/{subjectId}") public String getSubject(@PathVariable("subjectId") String subjectId) { return "this is get method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseT... | @Test public void getSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(get("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
BindController { @PostMapping(value = "/subject/{subjectId}") public String postSubject(@PathVariable("subjectId") String subjectId) { return "this is post method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String ba... | @Test public void postSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(post("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
BindController { @DeleteMapping(value = "/subject/{subjectId}") public String deleteSubject(@PathVariable("subjectId") String subjectId) { return "this is delete method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") Str... | @Test public void deleteSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(delete("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
BindController { @PutMapping(value = "/subject/{subjectId}") public String putSubject(@PathVariable("subjectId") String subjectId) { return "this is put method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseT... | @Test public void putSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(put("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
EmployeeService { @Transactional(rollbackFor = Exception.class) public void updateAgeById(Integer id, Integer age) { this.employeeRepository.updateAgeById(id, age); } @Transactional(rollbackFor = Exception.class) void updateAgeById(Integer id, Integer age); @Transactional(rollbackFor = Exception.class) void save(List<... | @Test public void updateAgeByIdTest() { EmployeeService employeeService = ctx.getBean(EmployeeService.class); employeeService.updateAgeById(1, 55); } |
HelloController { @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseBody public String say() { return girlProperties.getCupSize(); } @RequestMapping(method = RequestMethod.GET) String index(); @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseBody String say(); @GetMapping(value = "... | @Test public void say() throws Exception { String response = mockMvc.perform(get("/hello/say") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); } |
HelloController { @GetMapping(value = "/say/one") @ResponseBody public String sayOne(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) { return "id:" + myId; } @RequestMapping(method = RequestMethod.GET) String index(); @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseB... | @Test public void sayOne() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("id", "5"); String response = mockMvc.perform(get("/hello/say/one") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsStr... |
GirlController { @GetMapping public List<Girl> listGirl() { return girlRepository.findAll(); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirl... | @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); } |
BindController { @RequestMapping(value = "/baseType2") public String baseType2(Integer age) { return "age:" + age; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(St... | @Test public void baseType2() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("age", "20"); String response = mockMvc.perform(get("/baseType") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsStr... |
GirlController { @PostMapping public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) { if (bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); if (Objects.nonNull(fieldError)) { return ResultUtil.error(ResultUtil.RESPONSE_CODE_ERROR_PARAM, fieldError.getDefaultMessage... | @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() .getRes... |
GirlController { @GetMapping("/{id}") public Girl getGirlById(@PathVariable("id") Integer id) { return girlRepository.findById(id).orElse(null); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id... | @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 = objectMa... |
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> li... | @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... |
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); ... | @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); } |
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... | @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>>() { }; ... |
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... | @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); } |
TodoRepository { public void save(TodoItem item){ items.put(item.getName(),item); } void save(TodoItem item); TodoItem query(String name); } | @Test public void saveTest(){ TodoItem todoItem = new TodoItem("imooc"); repository.save(todoItem); Assert.assertNull(repository.query(todoItem.getName())); } |
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, Str... | @Test public void sendSimpleMail() { this.mailService.sendSimpleMail(TO, "这是第一封邮件", "大家好,这是我的第一封邮件"); } |
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(fro... | @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邮件", conten... |
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... | @Test public void sendAttachmentsMail() throws Exception { String filePath = "d:\\48-boot-mail-hello.zip"; this.mailService.sendAttachmentsMail(TO, "这是一封带附件的邮件", "这是一封带附件的邮件内容", new String[]{filePath}); } |
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") in... | @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() .getContentAsStr... |
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 MimeMessageHel... | @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"); c... |
HelloService { public void sayHello() { System.out.println("Hello World"); } void sayHello(); } | @Test public void sayHelloTest() { this.helloService.sayHello(); } |
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); In... | @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 = n... |
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>... | @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 = n... |
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... | @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("李四", "男",... |
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/... | @Test public void girlList() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("abc")); } |
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.getProp... | @Test public void testGetConnection() throws Exception { Connection connection = JDBCUtil.getConnection(); Assert.assertNotNull(connection); } |
EmployeeService { @Transactional public void update(Integer id, Integer age) { employeeRepository.update(id, age); } @Transactional void update(Integer id, Integer age); } | @Test public void testUpdate() { employeeService.update(1, 55); } |
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); @RequestMapp... | @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"); Str... |
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.getConn... | @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()); } } |
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 = connecti... | @Test public void testSave() { StudentDAO studentDAO = new StudentDAOImpl(); Student student = new Student(); student.setName("test"); student.setAge(30); studentDAO.save(student); } |
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 { in... | @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()); } } |
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 g... | @Test public void testSave() { Student student = new Student(); student.setName("test-spring-jdbc"); student.setAge(40); studentDAO.save(student); } |
SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager(
@SessionId Provider<Long> sessionIdProvider); Long getSessionId(); } | @Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals( sessionId2.longValue(), sessionId1.longValue()); } |
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 ad... | @Test public void testWithoutTransaction(){ demoService.addUser("tom"); } |
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") Integ... | @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); } |
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") St... | @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() .getRes... |
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(In... | @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()) .an... |
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... | @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 = objectMa... |
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> li... | @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... |
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 g... | @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); } |
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); @GetMap... | @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>>() { };... |
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 i... | @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); } |
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) @Ov... | @Test public void getSeckillList() throws Exception { List<Seckill> list = seckillService.getSeckillList(); logger.info("list={}",list); } |
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.cla... | @Test public void getById() throws Exception { long id = 1000L; Seckill seckill = seckillService.getById(id); logger.info("seckill={}", seckill); } |
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, Obje... | @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(exec... |
BeanAnnotation { public void say(String arg) { System.out.println("BeanAnnotation : " + arg); } void say(String arg); } | @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."); } |
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... | @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() .getContentAsSt... |
BeanAnnotation { void myHashCode() { System.out.println("BeanAnnotation : " + this.hashCode()); } void say(String arg); } | @Test public void testScpoe() { BeanAnnotation bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); } |
BeanScope { public void say() { System.out.println("BeanScope say : " + this.hashCode()); } void say(); } | @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.s... |
SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager(@SessionId Provider<Long> sessionIdProvider); Long getSessionId(); } | @Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals(sessionId1.longValue(), sessionId2.longValue()); } |
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(Or... | @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); } |
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... | @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(param... |
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... | @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.... |
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 = "/... | @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() .getContent... |
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[]... | @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() .getContentAs... |
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 || positionOffsetPixel... | @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 vo... |
ViewPagerAnimator implements ViewPager.OnPageChangeListener { public void destroy() { viewPager.removeOnPageChangeListener(this); } ViewPagerAnimator(@NonNull ViewPager viewPager,
@NonNull Provider<V> provider,
@NonNull Property<V> property,
... | @Test public void givenAnInitialisedIntegerAnimation_whenDestroyIt_thenItIsDetachedFromTheViewPager() { integerAnimator.destroy(); verify(integerViewPager, times(1)).removeOnPageChangeListener(eq(integerAnimator)); } |
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, nu... | @Test public void request(){ BitcoinCurse currentCurse = provider.getCurrentCurse(); assertNotNull(currentCurse.getDate()); assertNotNull(currentCurse.getCoin()); assertNotNull(currentCurse.getEuro()); BitcoinCurse currentCurse2 = provider.getCurrentCurse(); assertSame(currentCurse, currentCurse2); } |
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... | @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()); } |
SpeechService { public OutputSpeech readEvents(Locale locale, List<Event> events) { return readEvents(locale, "", events); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); Out... | @Test public void readEvents_empty(){ List<Event> events = Collections.emptyList(); final String moment = "heute"; final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("Es stehen " + moment + " keine Termine an.", result.getText()); }
@Test public void rea... |
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... | @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 a... |
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.toS... | @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 i... |
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); OutputSpee... | @Test public void speechNewEventSaved(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechNewEventSaved(aLocale); assertEquals("OK. Ich habe den Termin gespeichert.", result.getText()); } |
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... | @Test public void speechGeneralConfirmation(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechGeneralConfirmation(aLocale); assertEquals("OK.", result.getText()); } |
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 create... | @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(DateTim... |
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 calenda... | @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); ca... |
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()); ... | @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, ti... |
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 eventTim... | @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.... |
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); } | @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:Gr... |
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... | @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("<descr... |
NewEventSpeechlet { @OnIntent("NewEvent") public SpeechletResponse handleDialogAction(final IntentRequest request, final Session session) throws CalendarWriteException { session.setAttribute(BasicSpeechlet.KEY_DIALOG_TYPE, BasicSpeechlet.DIALOG_TYPE_NEW_EVENT); final SpeechletResponse response; try { switch (request.ge... | @Test public void inProgress_NotAllSlotsAreFilled() throws CalendarWriteException { final Session session = Session.builder() .withSessionId("<session-id>") .build(); final Intent intent = Intent.builder() .withName("<intent>") .withSlots(slots( slot("day", null) )) .build(); final IntentRequest request = IntentRequest... |
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(SE... | @Test public void inProgress_CalendarName() throws CalendarWriteException { checkCalendarName("geburtstag", "Geburtstage"); checkCalendarName("geburt", "Geburtstage"); checkCalendarName("termin", "Termine"); checkCalendarName("termine", "Termine"); checkCalendarName("haus", "Haushalt"); checkCalendarName("haushalt", "H... |
MessageService { public String de(String key, Object...args) { return String.format(messages.getOrDefault(key, key), args); } String de(String key, Object...args); } | @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); } |
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 spee... | @Test public void speechWelcomeMessage(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechWelcomeMessage(aLocale); assertEquals("Willkommen in deinem Kalender.", result.getText()); } |
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 speechGene... | @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()); } |
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())... | @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(Custom... |
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(); } | @Test public void testGetUrls() { final ClassLoader classLoader = ErraiAppPropertiesFilesTest.class.getClassLoader(); final List<URL> urls = ErraiAppPropertiesFiles.getUrls(classLoader); assertEquals(3, urls.size()); } |
ErraiAppPropertiesFiles { public static List<URL> getModulesUrls() { return getModulesUrls(ErraiAppPropertiesFiles.class.getClassLoader()); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); } | @Test public void testGetModuleUrls() { final List<URL> moduleUrls = ErraiAppPropertiesFiles.getModulesUrls(); assertEquals(2, moduleUrls.size()); } |
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); ... | @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 MalformedURLE... |
Properties { public static Map<String, String> load(final String data) { final ParseState parseState = new ParseState(data); while (parseState.next()); return parseState.properties; } private Properties(); static Map<String, String> load(final String data); } | @Test public void parsePropertiesWithEquals() { final String data = "key1=value1\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); }
@Test public void parsePropertiesWithColon() thr... |
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 p... | @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 testRemoveAllE... |
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... | @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 = elemental2DomU... |
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,... | @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)); } |
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);... | @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 clas... |
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.getMethodFro... | @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 am... |
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.get... | @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> annota... |
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));... | @Test public void testConverters() { try { assertThat(reflections.getConverters(C2.class, C3.class), are(C4.class.getDeclaredMethod("c2toC3", C2.class))); } catch (NoSuchMethodException e) { fail(); } } |
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... scanner... | @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()... |
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... | @Test public void isLoggedInReturnsFalseWhenNoUserLoggedIn() throws Exception { assertFalse(authService.isLoggedIn()); } |
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... | @Test public void getUserReturnsAnonymousWhenNoUserLoggedIn() throws Exception { assertEquals(User.ANONYMOUS, authService.getUser()); } |
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 Authentication... | @Test public void logoutIsIdempotent() throws Exception { authService.logout(); authService.logout(); isLoggedInReturnsFalseWhenNoUserLoggedIn(); } |
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.");... | @Test(expected = AlreadyLoggedInException.class) public void loginFailsIfKeycloakUserLoggedIn() throws Exception { getUserReturnsUserWhenKeycloakUserLoggedIn(); authService.login(PREFERRED_USERNAME, ""); } |
KeycloakAuthenticationService implements AuthenticationService, Serializable { void setSecurityContext(final KeycloakSecurityContext keycloakSecurityContext) { if (wrappedAuthService.isLoggedIn() && keycloakSecurityContext != null) { throw new AlreadyLoggedInException("Logged in as " + wrappedAuthService.getUser()); } ... | @Test(expected = AlreadyLoggedInException.class) public void settingKeycloakUserFailsIfWrappedUserLoggedIn() throws Exception { getUserReturnsUserWhenWrappedUserLoggedIn(); authService.setSecurityContext(securityContext); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.