method2testcases
stringlengths 118
3.08k
|
---|
### 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:
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 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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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)); } |
### Question:
SequentialActionGroup extends ActionGroupBase { @Override public final void execute() { if (mCurrentAction == null) { startNextAction(); } handleCurrentAction(); } SequentialActionGroup(Scheduler scheduler, Clock clock,
Collection<Action> actions, Queue<ActionContext> actionQueue); SequentialActionGroup(Clock clock); SequentialActionGroup(); @Override SequentialActionGroup add(Action action); @Override SequentialActionGroup add(Action... actions); @Override SequentialActionGroup add(Collection<Action> actions); @Override SequentialActionGroup andThen(Action... actions); @Override final void initialize(); @Override final void execute(); @Override boolean isFinished(); @Override void end(boolean wasInterrupted); }### Answer:
@Test public void execute_noActionCurrentlyRunning_startsNextAction() throws Exception { List<Action> actions = Collections.singletonList( ActionsMock.actionMocker().build() ); ActionContext context = mock(ActionContext.class); Deque<ActionContext> contexts = new ArrayDeque<>(Collections.singleton( context )); SequentialActionGroup actionGroup = new SequentialActionGroup( mock(Scheduler.class), mClock, actions, contexts); actionGroup.execute(); verify(context, times(1)).prepareForRun(); } |
### Question:
PeriodicAction extends ActionBase { @Override public void execute() { if (!mNextRun.isValid() || mClock.currentTime().largerThanOrEquals(mNextRun)) { mRunnable.run(); mNextRun = mClock.currentTime().add(mPeriod); } } PeriodicAction(Clock clock, Runnable runnable, Time period, Time nextRun); PeriodicAction(Clock clock, Runnable runnable, Time period); PeriodicAction(Runnable runnable, Time period); @Override void initialize(); @Override void execute(); }### Answer:
@Test public void execute_notFirstRunTimeHasElapsed_runsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(1); when(mClock.currentTime()).thenReturn(nextRun); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, times(1)).run(); }
@Test public void execute_notFirstRunTimeNotElapsed_notRunsRunnable() throws Exception { Runnable runnable = mock(Runnable.class); Time nextRun = Time.seconds(2); when(mClock.currentTime()).thenReturn(Time.seconds(1)); PeriodicAction action = new PeriodicAction(mClock, runnable, Time.seconds(1), nextRun); action.execute(); verify(runnable, never()).run(); } |
### Question:
DoubleBuffer { public void write(T value) { int index = mReadIndex.get(); mArray.set(index, value); mReadIndex.updateAndGet(mReadIndexUpdater); } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }### Answer:
@Test public void write_ofObject_writesObjectToWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.write(VALUE); assertEquals(VALUE, innerArray.get(0)); }
@Test public void write_ofObject_swapsWriteIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); doubleBuffer.write(VALUE); assertEquals(1, readIndex.get()); } |
### Question:
Time implements Comparable<Time> { public boolean equals(Time other) { return CompareResult.EQUAL_TO.is(compareTo(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 equals_thisIsNotValidOtherIsNotValid_returnsTrue() throws Exception { final Time THIS = Time.INVALID; final Time OTHER = Time.INVALID; assertTrue(THIS.equals(OTHER)); } |
### Question:
DoubleBuffer { public T read() { T value = mArray.get(mReadIndex.get()); if (value == null) { throw new NoSuchElementException("nothing to read"); } return value; } DoubleBuffer(AtomicReferenceArray<T> array, AtomicInteger readIndex); DoubleBuffer(); T read(); void write(T value); }### Answer:
@Test public void read_initialValues_throwsNoSuchElementException() throws Exception { assertThrows(NoSuchElementException.class, ()->{ AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); doubleBuffer.read(); }); }
@Test public void read_valueExistsInArray_returnsThatValue() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, new AtomicInteger(0)); Object read = doubleBuffer.read(); assertEquals(VALUE, read); }
@Test public void read_withIndexOnItem_swapsReadIndex() throws Exception { final Object VALUE = new Object(); AtomicReferenceArray<Object> innerArray = new AtomicReferenceArray<>(2); innerArray.set(0, VALUE); AtomicInteger readIndex = new AtomicInteger(0); DoubleBuffer<Object> doubleBuffer = new DoubleBuffer<>(innerArray, readIndex); Object value = doubleBuffer.read(); assertEquals(VALUE, value); } |
### Question:
SyncPipeJunction implements Pipeline<T> { @Override public void process(T input) throws VisionException { for (Pipeline<? super T> pipeline : mPipelines) { pipeline.process(input); } } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }### Answer:
@Test public void process_forInput_passesToAllPipes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Object INPUT = new Object(); SyncPipeJunction<Object> syncPipeJunction = new SyncPipeJunction<>(PIPELINES); syncPipeJunction.process(INPUT); for (Pipeline pipeline : PIPELINES) { verify(pipeline, times(1)).process(eq(INPUT)); } } |
### Question:
SyncPipeJunction implements Pipeline<T> { @Override public Pipeline<T> divergeTo(Pipeline<? super T> pipeline) { mPipelines.add(pipeline); return this; } SyncPipeJunction(Collection<Pipeline<? super T>> pipelines); @SafeVarargs SyncPipeJunction(Pipeline<? super T>... pipelines); @Override void process(T input); @Override Pipeline<T> divergeTo(Pipeline<? super T> pipeline); }### Answer:
@Test public void divergeTo_forNewPipeline_addsPipelineToJunctionWithPreviousOnes() throws Exception { final Pipeline[] PIPELINES = { mock(Pipeline.class), mock(Pipeline.class), mock(Pipeline.class) }; final Pipeline<? super Object> NEW_PIPELINE = mock(Pipeline.class); Collection<Pipeline> pipelines = new ArrayList<>(Arrays.asList(PIPELINES)); SyncPipeJunction syncPipeJunction = new SyncPipeJunction(pipelines); syncPipeJunction.divergeTo(NEW_PIPELINE); assertThat(pipelines, containsInRelativeOrder(PIPELINES)); assertThat(pipelines, hasItem(NEW_PIPELINE)); } |
### Question:
ProcessorPair implements Processor<T, R2> { @Override public R2 process(T input) throws VisionException { R out = mIn.process(input); return mOut.process(out); } ProcessorPair(Processor<T, R> in, Processor<? super R, R2> out); @Override R2 process(T input); }### Answer:
@Test public void process_forInput_processesInAndPipesToOut() throws Exception { final Object INPUT = new Object(); final Object OUTPUT_IN = new Object(); final Processor<Object, Object> PROCESSOR_IN = mock(Processor.class); when(PROCESSOR_IN.process(eq(INPUT))).thenReturn(OUTPUT_IN); final Processor<Object, Object> PROCESSOR_OUT = mock(Processor.class); ProcessorPair<Object, Object, Object> processorPair = new ProcessorPair<>(PROCESSOR_IN, PROCESSOR_OUT); processorPair.process(INPUT); verify(PROCESSOR_IN, times(1)).process(eq(INPUT)); verify(PROCESSOR_OUT, times(1)).process(eq(OUTPUT_IN)); } |
### Question:
InProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { mPipeline.process(input); return mProcessor.process(input); } InProcessorJunction(Processor<T, R> processor, Pipeline<? super T> pipeline); @Override R process(T input); @Override Processor<T, R> divergeIn(Pipeline<? super T> pipeline); }### Answer:
@Test public void process_forInput_processesAndPipesInputToPipeline() throws Exception { final Object INPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); final Pipeline<Object> PIPELINE = mock(Pipeline.class); InProcessorJunction<Object, Object> inProcessorJunction = new InProcessorJunction<>(PROCESSOR, PIPELINE); inProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(INPUT)); } |
### Question:
OutProcessorJunction implements Processor<T, R> { @Override public R process(T input) throws VisionException { R out = mProcessor.process(input); mPipeline.process(out); return out; } OutProcessorJunction(Processor<T, R> processor, Pipeline<? super R> pipeline); @Override R process(T input); @Override Processor<T, R> divergeOut(Pipeline<? super R> pipeline); }### Answer:
@Test public void process_forInput_processesAndPipesOutputToPipeline() throws Exception { final Object INPUT = new Object(); final Object OUTPUT = new Object(); final Processor<Object, Object> PROCESSOR = mock(Processor.class); when(PROCESSOR.process(eq(INPUT))).thenReturn(OUTPUT); final Pipeline<Object> PIPELINE = mock(Pipeline.class); OutProcessorJunction<Object, Object> outProcessorJunction = new OutProcessorJunction<>(PROCESSOR, PIPELINE); outProcessorJunction.process(INPUT); verify(PROCESSOR, times(1)).process(eq(INPUT)); verify(PIPELINE, times(1)).process(eq(OUTPUT)); } |
### Question:
SPARQLBasedTrivialInconsistencyFinder extends AbstractTrivialInconsistencyFinder { @Override public void run(boolean resume) { for(AbstractTrivialInconsistencyFinder checker : incFinders){ if(!(checker instanceof InverseFunctionalityBasedInconsistencyFinder) || isApplyUniqueNameAssumption()){ try { checker.run(resume); fireNumberOfConflictsFound(checker.getExplanations().size()); if(checker.terminationCriteriaSatisfied()){ break; } } catch (Exception e) { e.printStackTrace(); } } } if(!terminationCriteriaSatisfied()){ fireFinished(); completed = true; } } SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks); SPARQLBasedTrivialInconsistencyFinder(SparqlEndpointKS ks, InconsistencyType... inconsistencyTypes); void setInconsistencyTypes(InconsistencyType... inconsistencyTypes); @Override void setApplyUniqueNameAssumption(boolean applyUniqueNameAssumption); @Override void setStopIfInconsistencyFound(boolean stopIfInconsistencyFound); @Override void setAxiomsToIgnore(Set<OWLAxiom> axiomsToIgnore); @Override void addProgressMonitor(SPARQLBasedInconsistencyProgressMonitor mon); @Override void run(boolean resume); boolean isCompleted(); static void main(String[] args); }### Answer:
@Test public void testRun() { incFinder.run(); }
@Test public void testGetExplanations() { incFinder.run(); Set<Explanation<OWLAxiom>> explanations = incFinder.getExplanations(); for (Explanation<OWLAxiom> explanation : explanations) { System.out.println(explanation.getAxioms()); } } |
### Question:
GenerateTradeData { public List<Trade> createRandomData(int number) throws Exception { return null; } Trade createTradeData(int number, List<Party> partyList,
List<Instrument> instrumentList); List<Trade> createRandomData(int number); }### Answer:
@Test public void testGenerateRandomInstrument() throws Exception { GenerateRandomInstruments ranIns = new GenerateRandomInstruments(); assert (ranIns.createRandomData(50).size() == 50); }
@Test public void testGeneratePartyData() throws Exception { GenerateRandomParty ransPty = new GenerateRandomParty(); assert (ransPty.createRandomData(50).size() == 50); } |
### Question:
MergedItem { static MergedItem newInjectedRow(int type) { return new MergedItem(type, type, true); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }### Answer:
@Test public void testNewInjectedRowBuilder() { MergedItem mergedItem = MergedItem.newInjectedRow(1); assertThat(mergedItem.injected, is(true)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(1L)); } |
### Question:
MergedItem { static MergedItem newRow(int type, long id) { return new MergedItem(type, id, false); } private MergedItem(int type, long id, boolean injected); @Override boolean equals(Object o); }### Answer:
@Test public void testNewRowBuilder() { MergedItem mergedItem = MergedItem.newRow(1, 2L); assertThat(mergedItem.injected, is(false)); assertThat(mergedItem.type, is(1)); assertThat(mergedItem.id, is(2L)); }
@Test public void testMergedItemEqual() { MergedItem mergedItem1 = MergedItem.newRow(1, 2L); MergedItem mergedItem2 = MergedItem.newRow(1, 2L); MergedItem mergedItem3 = MergedItem.newRow(1, 3L); assertThat(mergedItem1, is(mergedItem2)); assertThat(mergedItem1, is(not(mergedItem3))); } |
### Question:
VectorCalculator { int[] calculateFromChildItemPositionTranslationVector() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int vectorSize = maxInjectedItemPosition - dataProvider.getInjectedItemCount() + 2; int[] vector = new int[vectorSize]; int accumulator = 0; int vectorIndex = 0; for (int i = 0; vectorIndex < vectorSize; i++) { if (!dataProvider.isItemInjectedOnPosition(i)) { vector[vectorIndex++] = accumulator; } else { accumulator++; } } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }### Answer:
@Test public void calculateFromChildItemPositionTranslationVector() throws Exception { testFromChildVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 3, 4 }); testFromChildVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 2, 4, 5 }); } |
### Question:
VectorCalculator { int[] calculateNumberOfInjectedItemsUpToPosition() { int maxInjectedItemPosition = getMaxInjectedItemPosition(); if (maxInjectedItemPosition != NO_POSITION) { int[] vector = new int[maxInjectedItemPosition + 1]; int previousValue = 0; for (int i = 0; i < vector.length; i++) { vector[i] = previousValue + (dataProvider.isItemInjectedOnPosition(i) ? 1 : 0); previousValue = vector[i]; } return vector; } else { return EMPTY_VECTOR; } } VectorCalculator(DataProvider dataProvider); }### Answer:
@Test public void calculateNumberOfInjectedItemsUpToPosition() throws Exception { testNumberOfInjectedItemsVectorValue(Collections.<Integer>emptyList(), new int[]{ 0 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); }}, new int[]{ 1 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(1); add(2); add(3); add(5); }}, new int[]{ 0, 1, 2, 3, 3, 4 }); testNumberOfInjectedItemsVectorValue(new ArrayList<Integer>() {{ add(0); add(2); add(4); add(5); add(7); }}, new int[]{ 1, 1, 2, 2, 3, 4, 4, 5 }); } |
### Question:
MergedListDiffer extends DiffUtil.Callback { void updateData(List<MergedItem> oldList, List<MergedItem> newList) { this.oldList = oldList; this.newList = newList; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer:
@Test public void returnsCorrectSizeOfOldList() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, Collections.<MergedItem>emptyList()); } |
### Question:
MergedListDiffer extends DiffUtil.Callback { @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { MergedItem oldRow = oldList.get(oldItemPosition); MergedItem newRow = newList.get(newItemPosition); return oldRow.type == newRow.type && oldRow.id == newRow.id; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer:
@Test public void testAreItemsTheSame() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); mergedListDiffer.updateData(new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(3)); }}, new ArrayList<MergedItem>() {{ add(MergedItem.newInjectedRow(2)); add(MergedItem.newInjectedRow(4)); }}); assertThat(mergedListDiffer.areItemsTheSame(0, 0), is(true)); assertThat(mergedListDiffer.areItemsTheSame(1, 1), is(false)); } |
### Question:
MergedListDiffer extends DiffUtil.Callback { @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return true; } @Override int getOldListSize(); @Override int getNewListSize(); @Override boolean areItemsTheSame(int oldItemPosition, int newItemPosition); @Override boolean areContentsTheSame(int oldItemPosition, int newItemPosition); }### Answer:
@Test public void areContentsTheSameAlwaysReturnsTrue() { MergedListDiffer mergedListDiffer = new MergedListDiffer(); assertThat(mergedListDiffer.areContentsTheSame(1, 1), is(true)); } |
### Question:
DMatrixSvd { public int rank() { double eps = ulp(1.0); double tol = max(_m,_n)*_s[0]*eps; int r = 0; for (int i=0; i<_mn; ++i) { if (_s[i]>tol) ++r; } return r; } DMatrixSvd(DMatrix a); DMatrix getU(); DMatrix getS(); double[] getSingularValues(); DMatrix getV(); DMatrix getVTranspose(); double norm2(); double cond(); int rank(); }### Answer:
@Test public void testRank() { DMatrix a = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, }); DMatrixSvd svda = new DMatrixSvd(a); assertEqualExact(svda.rank(),2); DMatrix b = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, {0.0, 0.0}, }); DMatrixSvd svdb = new DMatrixSvd(b); assertEqualExact(svdb.rank(),2); DMatrix c = new DMatrix(new double[][]{ {1.0, 3.0, 0.0}, {7.0, 9.0, 0.0}, }); DMatrixSvd svdc = new DMatrixSvd(c); assertEqualExact(svdc.rank(),2); } |
### Question:
TridiagonalFMatrix { public void solve(float[] r, float[] u) { if (_w==null) _w = new float[_n]; float t = _b[0]; u[0] = r[0]/t; for (int j=1; j<_n; ++j) { _w[j] = _c[j-1]/t; t = _b[j]-_a[j]*_w[j]; u[j] = (r[j]-_a[j]*u[j-1])/t; } for (int j=_n-1; j>0; --j) u[j-1] -= _w[j]*u[j]; } TridiagonalFMatrix(int n); TridiagonalFMatrix(int n, float[] a, float[] b, float[] c); int n(); float[] a(); float[] b(); float[] c(); void solve(float[] r, float[] u); float[] times(float[] x); void times(float[] x, float[] y); }### Answer:
@Test public void testSolve() { int n = 100; float[] a = randfloat(n); float[] b = randfloat(n); float[] c = randfloat(n); for (int i=0; i<n; ++i) b[i] += a[i]+c[i]; TridiagonalFMatrix t = new TridiagonalFMatrix(n,a,b,c); float[] r = randfloat(n); float[] u = zerofloat(n); t.solve(r,u); float[] s = t.times(u); assertEqualFuzzy(r,s); } |
### Question:
DMatrixQrd { public boolean isFullRank() { for (int j=0; j<_n; ++j) { if (_rdiag[j]==0.0) return false; } return true; } DMatrixQrd(DMatrix a); boolean isFullRank(); DMatrix getQ(); DMatrix getR(); DMatrix solve(DMatrix b); }### Answer:
@Test public void testRankDeficient() { DMatrix a = new DMatrix(new double[][]{ {0.0, 0.0}, {3.0, 4.0}, }); DMatrixQrd qrd = new DMatrixQrd(a); assertFalse(qrd.isFullRank()); } |
### Question:
Units implements Cloneable { public static synchronized boolean define(String name, boolean plural, String definition) throws UnitsFormatException { return addDefinition(name,plural,definition); } Units(); Units(String definition); Object clone(); boolean equals(Object object); boolean equals(Units units); float toSI(float value); double toSI(double value); float fromSI(float value); double fromSI(double value); float floatShiftFrom(Units units); double doubleShiftFrom(Units units); float floatScaleFrom(Units units); double doubleScaleFrom(Units units); boolean haveDimensions(); boolean haveDimensionsOf(Units units); String standardDefinition(); static Units add(Units units, double s); static Units sub(Units units, double s); static Units mul(Units units, double s); static Units div(Units units, double s); static Units mul(Units units1, Units units2); static Units div(Units units1, Units units2); static Units inv(Units units); static Units pow(Units units, int p); static synchronized boolean define(String name, boolean plural,
String definition); static synchronized boolean isValidDefinition(String definition); static synchronized boolean isDefined(String name); }### Answer:
@Test public void testDefine() { boolean isValid, defined; try { isValid = Units.isValidDefinition("degrees F"); assertTrue(isValid); Units.define("degrees F",false,"degF"); defined = Units.isDefined("degrees F"); assertTrue(defined); isValid = Units.isValidDefinition("degrees C"); assertTrue(isValid); Units.define("degrees C",false,"degC"); defined = Units.isDefined("degrees C"); assertTrue(defined); Units.define("cubic_inches",false,"in^3"); defined = Units.isDefined("m"); assertTrue(defined); defined = Units.define("m",false,"meters"); assertTrue(!defined); } catch (UnitsFormatException e) { assertTrue(false); } defined = true; try { Units.define("foo_inches",false,"foo inches"); } catch (UnitsFormatException e) { defined = false; } assertTrue(!defined); } |
### Question:
Parallel { public static void loop(int end, LoopInt body) { loop(0,end,1,1,body); } static void loop(int end, LoopInt body); static void loop(int begin, int end, LoopInt body); static void loop(int begin, int end, int step, LoopInt body); static void loop(
int begin, int end, int step, int chunk, LoopInt body); static V reduce(int end, ReduceInt<V> body); static V reduce(int begin, int end, ReduceInt<V> body); static V reduce(
int begin, int end, int step, ReduceInt<V> body); static V reduce(
int begin, int end, int step, int chunk, ReduceInt<V> body); static void setParallel(boolean parallel); }### Answer:
@Test public void testUnsafe() { final Unsafe<Worker> nts = new Unsafe<Worker>(); loop(20,new LoopInt() { public void compute(int i) { Worker w = nts.get(); if (w==null) nts.set(w=new Worker()); w.work(); } }); } |
### Question:
Eigen { public static void solveSymmetric33(double[][] a, double[][] v, double[] d) { solveSymmetric33Jacobi(a,v,d); } static void solveSymmetric22(float[][] a, float[][] v, float[] d); static void solveSymmetric22(double[][] a, double[][] v, double[] d); static void solveSymmetric33(double[][] a, double[][] v, double[] d); static void solveSymmetric33Fast(
double[][] a, double[][] v, double[] d); }### Answer:
@Test public void testSymmetric33() { double[][] v = new double[3][3]; double[] d = new double[3]; int nrand = 10000; for (int irand=0; irand<nrand; ++irand) { double[][] a = makeRandomSymmetric33(); Eigen.solveSymmetric33(a,v,d); check(a,v,d); } }
@Test public void testSymmetric33Special() { double[][] v = new double[3][3]; double[] d = new double[3]; double[][][] as = {ASMALL,A100,A110,A111,ATEST1}; for (double[][] a:as) { Eigen.solveSymmetric33(a,v,d); check(a,v,d); } } |
### Question:
Real1 { public Real1 plus(Real1 ra) { return add(this,ra); } Real1(Sampling s); Real1(float[] v); Real1(Sampling s, float[] v); Real1(int n, double d, double f); Real1(int n, double d, double f, float[] v); Real1(Real1 r); Sampling getSampling(); float[] getValues(); Real1 resample(Sampling s); Real1 plus(Real1 ra); Real1 plus(float ar); Real1 convolve(Real1 ra); Sampling getFourierSampling(int nmin); static Real1 zero(int n); static Real1 zero(Sampling s); static Real1 fill(double ar, int n); static Real1 fill(double ar, Sampling s); static Real1 ramp(double fv, double dv, int nv); static Real1 ramp(double fv, double dv, Sampling s); static Real1 add(Real1 ra, Real1 rb); static Real1 add(float ar, Real1 rb); static Real1 add(Real1 ra, float br); static Real1 sub(Real1 ra, Real1 rb); static Real1 sub(float ar, Real1 rb); static Real1 sub(Real1 ra, float br); static Real1 mul(Real1 ra, Real1 rb); static Real1 mul(float ar, Real1 rb); static Real1 mul(Real1 ra, float br); static Real1 div(Real1 ra, Real1 rb); static Real1 div(float ar, Real1 rb); static Real1 div(Real1 ra, float br); }### Answer:
@Test public void testMath() { Real1 ra = RAMP1; Real1 rb = RAMP1; Real1 rc = ra.plus(rb); Real1 re = RAMP2; assertRealEquals(re,rc); } |
### Question:
ArrayQueue { public E first() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }### Answer:
@Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueFirstElementThrowsException() { aq.first(); } |
### Question:
Projector { public AxisScale getScale() { return _scaleType; } Projector(double v0, double v1); Projector(double v0, double v1, AxisScale scale); Projector(double v0, double v1, double u0, double u1); Projector(double v0, double v1, double u0, double u1, AxisScale s); Projector(Projector p); double u(double v); double v(double u); double u0(); double u1(); double v0(); double v1(); AxisScale getScale(); boolean isLinear(); boolean isLog(); void merge(Projector p); double getScaleRatio(Projector p); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testAutoLinear() { Projector p = new Projector(0.0, 100, 0.0, 1.0); assertTrue(p.getScale() == AxisScale.LINEAR); } |
### Question:
ArrayQueue { public E remove() { if (_size==0) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)_array[_first]; ++_first; if (_first==_length) _first = 0; --_size; if (_size*3<_length) resize(_size*2); return e; } ArrayQueue(); ArrayQueue(int capacity); void add(E e); E first(); E remove(); boolean isEmpty(); void ensureCapacity(int capacity); int size(); void trimToSize(); }### Answer:
@Test(expectedExceptions = NoSuchElementException.class) public void testEmptyQueueRemoveElementThrowsException() { aq.remove(); } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float get() { return f(_ai.get()); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testDefaultConstructor() { assertEquals(0.0,af.get(),epsilon); }
@Test public void testConstructorSingleParameter() { float expected = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected); assertEquals(expected,af.get(),epsilon); } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final void set(float value) { _ai.set(i(value)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testSet() { float expected = RANDOM.nextFloat(); af.set(expected); assertEquals(expected, af.get(),epsilon); } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float addAndGet(float delta) { for (;;) { int iexpect = _ai.get(); float expect = f(iexpect); float update = expect+delta; int iupdate = i(update); if (_ai.compareAndSet(iexpect,iupdate)) return update; } } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testAddAndGet() { float expected = 0.0f; float actual; for (int i=0; i<10; ++i) { float nf = RANDOM.nextFloat(); expected += nf; actual = af.addAndGet(nf); assertEquals(expected, actual,epsilon); } } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final boolean compareAndSet(float expect, float update) { return _ai.compareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testCompareAndSet() { af.compareAndSet(1.0f,2.0f); assertEquals(0.0f,af.get()); af.compareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final boolean weakCompareAndSet(float expect, float update) { return _ai.weakCompareAndSet(i(expect),i(update)); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testWeakCompareAndSet() { af.weakCompareAndSet(0.0f,1.0f); assertEquals(1.0f,af.get()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.