method2testcases
stringlengths
118
3.08k
### Question: Calculate { public String echo(String name) { return "Echo, echo, echo : " + name; } static void main(String[] args); String echo(String name); }### Answer: @Test public void whenTakeNameThenThreeEchoPlusName() { String input = "Denis Seleznev"; String expect = "Echo, echo, echo : Denis Seleznev"; Calculate calc = new Calculate(); String result = calc.echo(input); assertThat(result, is(expect)); }
### Question: FindLoop { public int indexOf(int[] data, int el) { int index = -1; for (int i = 0; i < data.length; i++) { if (data[i] == el) { index = i; break; } } return index; } int indexOf(int[] data, int el); }### Answer: @Test public void ifMassivOfSixElementsFindIndexContainsEight() { int[] data = {1, 15, 14, 8, 22}; FindLoop loop = new FindLoop(); int result = loop.indexOf(data, 8); assertThat(result, is(3)); } @Test public void ifMassivHasNotAFindNomber() { int[] data = {1, 3, 4}; FindLoop loop = new FindLoop(); int result = loop.indexOf(data, 5); assertThat(result, is(-1)); }
### Question: Square { public int[] calculate(int bound) { int[] arrSquares = new int[bound]; for (int i = 0; i < bound; i++) { arrSquares[i] = (int) Math.pow(i + 1, 2); } return arrSquares; } int[] calculate(int bound); }### Answer: @Test public void ifBoundEqualsFive() { Square arrSquares = new Square(); int[] result = arrSquares.calculate(5); int[] expect = {1, 4, 9, 16, 25}; assertThat(result, is(expect)); }
### Question: UserConvert { public HashMap<Integer, User> process(List<User> list) { HashMap<Integer, User> result = new HashMap<>(); for (User element : list) { result.put(element.getId(), element); } return result; } HashMap<Integer, User> process(List<User> list); }### Answer: @Test public void usersListConvertToHashMap() { List<User> userList = new ArrayList<>(); userList.add(new User(3, "Ivan", "Spb")); userList.add(new User(4, "Vasiliy", "Turinsk")); UserConvert convertTest = new UserConvert(); HashMap<Integer, User> result = convertTest.process(userList); assertThat(result.get(3).getName(), is("Ivan")); }
### Question: ArrayDuplicate { public String[] remove(String[] array) { int repeatedWords = 0; for (int wordIndex = 0; wordIndex < array.length - 1; wordIndex++) { for (int comparedWordIndex = 0; comparedWordIndex < array.length - 1 - repeatedWords; comparedWordIndex++) { if (comparedWordIndex == wordIndex) { comparedWordIndex++; } else if (array[wordIndex].equals(array[comparedWordIndex])) { String tmp = array[comparedWordIndex]; array[comparedWordIndex] = array[array.length - repeatedWords - 1]; array[array.length - repeatedWords - 1] = tmp; repeatedWords++; } } } return Arrays.copyOf(array, array.length - repeatedWords); } String[] remove(String[] array); }### Answer: @Test public void whenRemoveDuplicatesThenArrayWithoutDuplicate() { String[] array = {"Привет", "Мир", "Привет", "Супер", "Мир"}; String[] except = {"Привет", "Супер", "Мир"}; ArrayDuplicate duplicate = new ArrayDuplicate(); String[] result = duplicate.remove(array); assertThat(result, is(except)); }
### Question: Matrix { int[][] multiple(int size) { int[][] table = new int[size][size]; for (int axisI = 0; axisI < size; axisI++) { for (int axisJ = 0; axisJ < size; axisJ++) { table[axisI][axisJ] = (axisI + 1) * (axisJ + 1); } } return table; } }### Answer: @Test public void ifSizeOfMultipledTableEqualsThree() { Matrix matrix = new Matrix(); int[][] result = matrix.multiple(3); int[][] expect = { {1, 2, 3}, {2, 4, 6}, {3, 6, 9} }; assertThat(result, is(expect)); }
### Question: ArrayChar { public boolean startWith(String prefix) { boolean done = true; char[] value = prefix.toCharArray(); for (int i = 0; i < value.length; i++) { if (this.data[i] != value[i]) { done = false; break; } } return done; } ArrayChar(String line); boolean startWith(String prefix); }### Answer: @Test public void whenStartWithPrefixThenTrue() { ArrayChar word = new ArrayChar("Hello"); boolean result = word.startWith("He"); assertThat(result, is(true)); } @Test public void whenNotStartWithPrefixThenFalse() { ArrayChar word = new ArrayChar("Hello"); boolean result = word.startWith("Hi"); assertThat(result, is(false)); }
### Question: Turn { public int[] back(int[] array) { for (int arrayIndex = 0; arrayIndex < array.length / 2; arrayIndex++) { int oldArray = array[arrayIndex]; array[arrayIndex] = array[array.length - arrayIndex - 1]; array[array.length - arrayIndex - 1] = oldArray; } return array; } int[] back(int[] array); }### Answer: @Test public void whenTurnArrayWithEvenAmountOfElementsThenTurnedArray() { int[] data = {1, 2, 3, 4, 5}; Turn array = new Turn(); int[] result = array.back(data); int[] expect = {5, 4, 3, 2, 1}; assertThat(result, is(expect)); } @Test public void whenTurnArrayWithOddAmountOfElementsThenTurnedArray() { int[] data = {4, 1, 6, 2}; Turn array = new Turn(); int[] result = array.back(data); int[] expect = {2, 6, 1, 4}; assertThat(result, is(expect)); }
### Question: BubbleSort { public int[] sort(int[] sorted) { for (int sortArea = sorted.length; sortArea != 0; sortArea--) { for (int i = 0; i < sortArea - 1; i++) { if (sorted[i] > sorted[i + 1]) { int oldArray = sorted[i]; sorted[i] = sorted[i + 1]; sorted[i + 1] = oldArray; } } } return sorted; } int[] sort(int[] sorted); }### Answer: @Test public void whenSortArrayWithTenElementsThenSortedArray() { BubbleSort bubble = new BubbleSort(); int[] array = {1, 5, 4, 2, 3, 1, 7, 8, 0, 5}; int[] result = bubble.sort(array); int[] expect = {0, 1, 1, 2, 3, 4, 5, 5, 7, 8}; assertThat(result, is(expect)); }
### Question: ArrayChar2 { public boolean contains(String origin, String word) { boolean done = true; char[] aOrigin = origin.toCharArray(); char[] aWord = word.toCharArray(); for (int aOriginIndex = 0; aOriginIndex <= aOrigin.length - aWord.length; aOriginIndex++) { for (int aWordIndex = 0; aWordIndex < aWord.length; aWordIndex++) { if (aOrigin[aOriginIndex + aWordIndex] != aWord[aWordIndex]) { done = false; break; } else { done = true; } } if (done) { break; } } return done; } boolean contains(String origin, String word); }### Answer: @Test public void whenOriginWordContainsWordThenTrue() { ArrayChar2 word = new ArrayChar2(); boolean result = word.contains("Сумасшествие", "шест"); assertThat(result, is(true)); } @Test public void whenOriginWordNotContainsWordThenFalse() { ArrayChar2 word = new ArrayChar2(); boolean result = word.contains("Проверка", "Прок"); assertThat(result, is(false)); }
### Question: WordIndex { public void loadFile(String fileName) throws FileNotFoundException { Scanner fileScanner = new Scanner(new File(fileName)); int wordCounter = 0; while (fileScanner.hasNext()) { wordCounter++; storage.put(fileScanner.next().replaceAll("\\p{Punct}", ""), wordCounter); } } void loadFile(String fileName); Set<Integer> getIndicesForWord(String word); }### Answer: @Test(expected = FileNotFoundException.class) public void ifFileNotFoundThenThrowException() throws FileNotFoundException { WordIndex testIndex = new WordIndex(); testIndex.loadFile("incorrect way"); }
### Question: Max { public int max(int first, int second) { return first >= second ? first : second; } int max(int first, int second); int max(int first, int second, int third); }### Answer: @Test public void whenFirstLessSecond() { int result = maxim.max(1, 2); assertThat(result, is(2)); } @Test public void whenSecondLessFirst() { int result = maxim.max(3, 2); assertThat(result, is(3)); } @Test public void whenFirstEqualSecond() { int result = maxim.max(4, 4); assertThat(result, is(4)); } @Test public void whenFirstOfThreeNumbersMore() { int result = maxim.max(6, 4, 2); assertThat(result, is(6)); } @Test public void whenSecondofThreeNumbersMore() { int result = maxim.max(3, 10, 1); assertThat(result, is(10)); } @Test public void whenThirdOfThreeNumbersMore() { int result = maxim.max(4, 8, 15); assertThat(result, is(15)); } @Test public void whenThreeNumbersEquals() { int result = maxim.max(2, 2, 2); assertThat(result, is(2)); }
### Question: MusicTypeStore { public int add(MusicType type) { int typeId = 0; if (!this.findAll().contains(type)) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("addMusicType"))) { st.setString(1, type.getType()); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { typeId = rstSet.getInt("id"); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return typeId; } int add(MusicType type); int findTypeId(MusicType type); List<MusicType> findAll(); MusicType findById(int id); boolean delete(int id); boolean update(int id, MusicType type); }### Answer: @Test public void add() { this.testStore.add(new MusicType("test6")); assertTrue(this.testStore.findAll().contains(new MusicType("test6"))); }
### Question: MusicTypeStore { public List<MusicType> findAll() { List<MusicType> result = new ArrayList<>(); try (Connection connect = CON.getConnect(); Statement st = connect.createStatement(); ResultSet rstSet = st.executeQuery(QUERIES.getProperty("findAllTypes"))) { while (rstSet.next()) { MusicType founded = new MusicType(rstSet.getString("music_type")); founded.setId(rstSet.getInt("id")); result.add(founded); } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } int add(MusicType type); int findTypeId(MusicType type); List<MusicType> findAll(); MusicType findById(int id); boolean delete(int id); boolean update(int id, MusicType type); }### Answer: @Test public void findAll() { this.testStore.add(new MusicType("test6")); this.testStore.add(new MusicType("test7")); assertTrue(this.testStore.findAll().containsAll(asList(new MusicType("test6"), new MusicType("test7")))); }
### Question: MusicTypeStore { public MusicType findById(int id) { MusicType result = null; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("findTypeById"))) { st.setInt(1, id); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { result = new MusicType(rstSet.getString("music_type")); result.setId(rstSet.getInt("id")); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } int add(MusicType type); int findTypeId(MusicType type); List<MusicType> findAll(); MusicType findById(int id); boolean delete(int id); boolean update(int id, MusicType type); }### Answer: @Test public void findById() { this.testStore.add(new MusicType("test6")); int id = this.findIdByType(new MusicType("test6")); assertThat(this.testStore.findById(id), is(new MusicType("test6"))); assertNull(this.testStore.findById(0)); }
### Question: CycleCheck { public <T> boolean hasCycle(Node<T> first) { boolean result = false; if (first != null) { Node<T> slow = first; Node<T> fast = first; while (!result && slow.getNext() != null && fast.getNext() != null && fast.getNext().getNext() != null) { slow = slow.getNext(); fast = fast.getNext().getNext(); if (slow.equals(fast)) { result = true; } } } return result; } boolean hasCycle(Node<T> first); }### Answer: @Test public void ifListHasCycle() { first.setNext(two); two.setNext(third); third.setNext(four); four.setNext(first); assertThat(new CycleCheck().hasCycle(first), is(true)); } @Test public void ifListHasNotCycle() { first.setNext(two); two.setNext(third); third.setNext(four); four.setNext(null); assertThat(new CycleCheck().hasCycle(first), is(false)); } @Test public void ifListHasMediumCycle() { first.setNext(two); two.setNext(third); third.setNext(two); four.setNext(null); assertThat(new CycleCheck().hasCycle(first), is(true)); }
### Question: MusicTypeStore { public boolean delete(int id) { boolean result = false; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("deleteType"))) { st.setInt(1, id); result = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } int add(MusicType type); int findTypeId(MusicType type); List<MusicType> findAll(); MusicType findById(int id); boolean delete(int id); boolean update(int id, MusicType type); }### Answer: @Test public void delete() { this.testStore.add(new MusicType("test6")); int id = this.findIdByType(new MusicType("test6")); assertTrue(this.testStore.delete(id)); assertFalse(this.testStore.delete(id)); }
### Question: MusicTypeStore { public boolean update(int id, MusicType type) { boolean result = false; if (type != null) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("updateType"))) { st.setString(1, type.getType()); st.setInt(2, id); result = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return result; } int add(MusicType type); int findTypeId(MusicType type); List<MusicType> findAll(); MusicType findById(int id); boolean delete(int id); boolean update(int id, MusicType type); }### Answer: @Test public void update() { this.testStore.add(new MusicType("test6")); int id = this.findIdByType(new MusicType("test6")); assertTrue(this.testStore.update(id, new MusicType("test7"))); assertFalse(this.testStore.update(id, null)); assertFalse(this.testStore.update(0, new MusicType("test6"))); assertThat(this.testStore.findById(id).getType(), is("test7")); }
### Question: UserStore { public boolean add(User user) { boolean done = false; if (user != null && this.findByLogin(user.getLogin()) == null) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("insertUser"))) { int roleId = ROLE_STORE.findRoleId(user.getRole()); if (roleId == 0) { roleId = ROLE_STORE.add(user.getRole()); } st.setInt(1, roleId); st.setString(2, user.getPassword()); st.setString(3, user.getLogin()); st.setString(4, user.getName()); int userId = 0; try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { userId = rstSet.getInt("id"); ADDRESS_STORE.add(userId, user.getAddress()); done = true; } } this.insertUserType(userId, user); } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return done; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void add() { assertTrue(this.testStore.add(this.first)); assertTrue(this.testStore.findAll().contains(this.first)); }
### Question: UserStore { public List<User> findAll() { List<User> result = new ArrayList<>(); try (Connection con = CON.getConnect(); PreparedStatement st = con.prepareStatement(QUERIES.getProperty("findUsers")); ResultSet rstSet = st.executeQuery()) { while (rstSet.next()) { result.add(this.createUserByRstSet(rstSet)); } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void findAll() { this.testStore.add(this.first); this.testStore.add(this.second); assertTrue(this.testStore.findAll().containsAll(asList(this.first, this.second))); }
### Question: UserStore { public User findById(int id) { User result = null; try (Connection con = CON.getConnect(); PreparedStatement st = con.prepareStatement(QUERIES.getProperty("findUserById"))) { st.setInt(1, id); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { result = createUserByRstSet(rstSet); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void findById() { this.testStore.add(this.first); int userId = findIdByName(this.first); assertThat(this.testStore.findById(userId), is(this.first)); }
### Question: UserStore { public User findByAddress(Address address) { return this.findById(ADDRESS_STORE.findId(address)); } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void findByAddress() { this.testStore.add(this.first); assertThat(this.testStore.findByAddress(this.address), is(this.first)); }
### Question: UserStore { public List<User> findByRole(Role role) { List<User> result = new ArrayList<>(); try (Connection con = CON.getConnect(); PreparedStatement st = con.prepareStatement(QUERIES.getProperty("findUsersByRole"))) { st.setInt(1, ROLE_STORE.findRoleId(role)); try (ResultSet rstSet = st.executeQuery()) { while (rstSet.next()) { result.add(createUserByRstSet(rstSet)); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void findByRole() { this.testStore.add(this.first); this.testStore.add(this.second); this.testStore.add(this.third); assertTrue(this.testStore.findByRole(this.user).containsAll(asList(this.first, this.second))); assertFalse(this.testStore.findByRole(this.user).contains(this.third)); }
### Question: UserStore { public List<User> findByType(MusicType type) { List<User> result = new ArrayList<>(); try (Connection con = CON.getConnect(); PreparedStatement st = con.prepareStatement(QUERIES.getProperty("findUsersByType"))) { st.setInt(1, TYPE_STORE.findTypeId(type)); try (ResultSet rstSet = st.executeQuery()) { while (rstSet.next()) { result.add(createUserByRstSet(rstSet)); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void findByType() { this.testStore.add(this.first); this.testStore.add(this.second); this.testStore.add(this.third); assertTrue(this.testStore.findByType(this.rapMType).containsAll(asList(this.first, this.third))); assertFalse(this.testStore.findByType(this.rapMType).contains(this.second)); }
### Question: UserStore { public boolean delete(int id) { boolean done = false; if (ADDRESS_STORE.delete(id)) { try (Connection con = CON.getConnect()) { this.deleteUserType(con, id); try (PreparedStatement st2 = con.prepareStatement(QUERIES.getProperty("deleteUser"))) { st2.setInt(1, id); done = st2.executeUpdate() > 0; } } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return done; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void delete() { this.testStore.add(this.first); int userId = this.findIdByName(this.first); this.testStore.delete(userId); assertNull(this.testStore.findById(userId)); }
### Question: UserStore { public boolean update(int id, User user) { boolean done = false; if (ADDRESS_STORE.update(id, user.getAddress())) { try (Connection con = CON.getConnect(); PreparedStatement upUsr = con.prepareStatement(QUERIES.getProperty("updateUser"))) { upUsr.setInt(1, ROLE_STORE.findRoleId(user.getRole())); upUsr.setString(2, user.getPassword()); upUsr.setString(3, user.getLogin()); upUsr.setString(4, user.getName()); upUsr.setInt(5, id); upUsr.execute(); this.deleteUserType(con, id); this.insertUserType(id, user); done = true; } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return done; } boolean add(User user); List<User> findAll(); User findById(int id); User findByLogin(String login); User findByAddress(Address address); List<User> findByRole(Role role); List<User> findByType(MusicType type); boolean delete(int id); boolean update(int id, User user); }### Answer: @Test public void update() { this.testStore.add(this.first); int userId = this.findIdByName(this.first); this.testStore.update(userId, this.second); assertThat(this.testStore.findById(userId), is(this.second)); }
### Question: RoleStore { public int add(Role role) { int result = 0; if (role != null && !findAll().contains(role)) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("addRole"))) { st.setString(1, role.getRole()); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { result = rstSet.getInt("id"); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return result; } int add(Role role); List<Role> findAll(); Role findById(int id); boolean delete(int id); boolean update(int id, Role role); int findRoleId(Role role); List<User> findUsersByRole(Role role); }### Answer: @Test public void add() { testStore.add(new Role("test")); assertTrue(testStore.findAll().contains(new Role("test"))); }
### Question: RoleStore { public List<Role> findAll() { List<Role> result = new ArrayList<>(); try (Connection connect = CON.getConnect(); Statement st = connect.createStatement(); ResultSet rstSet = st.executeQuery(QUERIES.getProperty("findAllRoles"))) { while (rstSet.next()) { Role role = new Role(rstSet.getString("role")); role.setId(rstSet.getInt("id")); result.add(role); } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } int add(Role role); List<Role> findAll(); Role findById(int id); boolean delete(int id); boolean update(int id, Role role); int findRoleId(Role role); List<User> findUsersByRole(Role role); }### Answer: @Test public void findAll() { testStore.add(new Role("test")); testStore.add(new Role("test2")); assertTrue(testStore.findAll().containsAll(asList(new Role("test"), new Role("test2")))); }
### Question: RoleStore { public Role findById(int id) { Role result = null; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("findRoleById"))) { st.setInt(1, id); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { result = new Role(rstSet.getString("role")); result.setId(rstSet.getInt("id")); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } int add(Role role); List<Role> findAll(); Role findById(int id); boolean delete(int id); boolean update(int id, Role role); int findRoleId(Role role); List<User> findUsersByRole(Role role); }### Answer: @Test public void findById() { this.testStore.add(new Role("test")); int roleId = findRoleId(new Role("test")); assertTrue(this.testStore.findById(roleId).equals(new Role("test"))); }
### Question: RoleStore { public boolean delete(int id) { boolean done = false; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("deleteRole"))) { st.setInt(1, id); done = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } return done; } int add(Role role); List<Role> findAll(); Role findById(int id); boolean delete(int id); boolean update(int id, Role role); int findRoleId(Role role); List<User> findUsersByRole(Role role); }### Answer: @Test public void delete() { this.testStore.add(new Role("test")); assertTrue(this.testStore.delete(this.findRoleId(new Role("test")))); assertFalse(this.testStore.delete(0)); assertFalse(this.testStore.findAll().contains(new Role("test"))); }
### Question: RoleStore { public boolean update(int id, Role role) { boolean done = false; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("updateRole"))) { st.setString(1, role.getRole()); st.setInt(2, id); done = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } return done; } int add(Role role); List<Role> findAll(); Role findById(int id); boolean delete(int id); boolean update(int id, Role role); int findRoleId(Role role); List<User> findUsersByRole(Role role); }### Answer: @Test public void update() { Role role = new Role("test"); Role uppedRole = new Role("test2"); this.testStore.add(role); int roleId = this.findRoleId(role); assertTrue(this.testStore.update(roleId, uppedRole)); assertFalse(this.testStore.update(0, new Role("test3"))); assertTrue(this.testStore.findById(roleId).equals(uppedRole)); assertFalse(this.testStore.findAll().contains(role)); }
### Question: AddressStore { public boolean add(int userId, Address address) { boolean result = false; if (address != null) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("addAddress"))) { st.setInt(1, userId); st.setString(2, address.getAddress()); st.execute(); result = true; } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return result; } boolean add(int userId, Address address); List<Address> findAll(); Address findById(int id); boolean delete(int id); boolean update(int id, Address address); int findId(Address address); }### Answer: @Test public void add() { assertTrue(this.testStore.add(-1, new Address("test"))); assertThat(this.testStore.findById(-1).getAddress(), is("test")); assertFalse(this.testStore.add(1, null)); }
### Question: AddressStore { public List<Address> findAll() { List<Address> result = new ArrayList<>(); try (Connection connect = CON.getConnect(); Statement st = connect.createStatement()) { try (ResultSet rstSet = st.executeQuery(QUERIES.getProperty("findAllAddress"))) { while (rstSet.next()) { result.add(new Address(rstSet.getString("address"))); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(int userId, Address address); List<Address> findAll(); Address findById(int id); boolean delete(int id); boolean update(int id, Address address); int findId(Address address); }### Answer: @Test public void findAll() { this.testStore.add(-1, new Address("test")); this.testStore.add(-2, new Address("test2")); assertTrue(this.testStore.findAll().containsAll(asList(new Address("test"), new Address("test2")))); }
### Question: AddressStore { public Address findById(int id) { Address result = null; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("findAddressById"))) { st.setInt(1, id); try (ResultSet rstSet = st.executeQuery()) { if (rstSet.next()) { result = new Address(rstSet.getString("address")); } } } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(int userId, Address address); List<Address> findAll(); Address findById(int id); boolean delete(int id); boolean update(int id, Address address); int findId(Address address); }### Answer: @Test public void findById() { this.testStore.add(-1, new Address("test")); assertThat(this.testStore.findById(-1), is(new Address("test"))); }
### Question: AddressStore { public boolean delete(int id) { boolean result = false; try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("deleteAddress"))) { st.setInt(1, id); result = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } return result; } boolean add(int userId, Address address); List<Address> findAll(); Address findById(int id); boolean delete(int id); boolean update(int id, Address address); int findId(Address address); }### Answer: @Test public void delete() { this.testStore.add(-1, new Address("test")); assertTrue(this.testStore.delete(-1)); assertFalse(this.testStore.delete(-1)); assertNull(this.testStore.findById(-1)); }
### Question: AddressStore { public boolean update(int id, Address address) { boolean result = false; if (address != null) { try (Connection connect = CON.getConnect(); PreparedStatement st = connect.prepareStatement(QUERIES.getProperty("updateAddress"))) { st.setString(1, address.getAddress()); st.setInt(2, id); result = st.executeUpdate() > 0; } catch (SQLException e) { LOG.error(e.getMessage(), e); } } return result; } boolean add(int userId, Address address); List<Address> findAll(); Address findById(int id); boolean delete(int id); boolean update(int id, Address address); int findId(Address address); }### Answer: @Test public void update() { this.testStore.add(-1, new Address("test")); assertTrue(this.testStore.update(-1, new Address("test2"))); assertFalse(this.testStore.update(-100, new Address("test3"))); assertFalse(this.testStore.update(-1, null)); assertThat(this.testStore.findById(-1).getAddress(), is("test2")); }
### Question: Count { public synchronized int get() { return this.value; } synchronized void increment(); synchronized int get(); }### Answer: @Test public void whenExecute2ThreadThen2() throws InterruptedException { final Count count = new Count(); Thread first = new ThreadCount(count); Thread second = new ThreadCount(count); first.start(); second.start(); first.join(); second.join(); assertThat(count.get(), is(2)); }
### Question: DeadLock implements Runnable { DeadLock(CyclicBarrier barrier) { this.barrier = barrier; } DeadLock(CyclicBarrier barrier); void setOther(DeadLock other); @Override void run(); }### Answer: @Ignore @Test public void deadLock() { CyclicBarrier barrier = new CyclicBarrier(2); DeadLock a = new DeadLock(barrier); DeadLock b = new DeadLock(barrier); a.setOther(b); b.setOther(a); Thread first = new Thread(a); Thread second = new Thread(b); first.start(); second.start(); try { second.join(); first.join(); } catch (InterruptedException e) { e.printStackTrace(); } }
### Question: Lock { public synchronized void lock() { while (this.lockOwner != null && !this.lockOwner.equals(Thread.currentThread())) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.lockOwner = Thread.currentThread(); } synchronized void lock(); synchronized void unLock(); }### Answer: @Test public void lockTest() { ConcurrentLinkedQueue<String> result = new ConcurrentLinkedQueue<>(); Lock lock = new Lock(); Thread first = new Thread(() -> { lock.lock(); result.add("first get lock"); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } lock.unLock(); result.add("first unlock lock"); }); Thread second = new Thread(() -> { try { Thread.sleep(400); } catch (InterruptedException e) { e.printStackTrace(); } lock.unLock(); lock.lock(); result.add("second get lock"); lock.unLock(); result.add("second unlock lock"); }); first.setName("first"); second.setName("second"); first.start(); second.start(); try { first.join(); second.join(); } catch (InterruptedException e) { e.printStackTrace(); } String[] arr = new String[4]; result.toArray(arr); assertThat(arr, is(new String[]{ "first get lock", "first unlock lock", "second get lock", "second unlock lock" })); }
### Question: Board { public int getSize() { return this.board.length; } Board(int size); void init(final int difficultyLevel); ReentrantLock getLock(Cell cell); int getSize(); }### Answer: @Test public void ifCreateNewBoardWithSize10ThenGetSizeShouldBeReturn10() { Board testBoard = new Board(10); assertThat(testBoard.getSize(), is(10)); }
### Question: SimpleLinkedList implements SimpleList<E> { @Override public synchronized Iterator<E> iterator() { return new Iterator<E>() { private int nodeCount; private final int expectedModCount = modCount; private Node<E> currentNode = first; @Override public boolean hasNext() { return this.nodeCount < size; } @Override public E next() { if (this.expectedModCount != modCount) { throw new ConcurrentModificationException(); } if (this.nodeCount >= size) { throw new NoSuchElementException(); } E result = this.currentNode.item; this.currentNode = this.currentNode.next; this.nodeCount++; return result; } }; } synchronized int getSize(); @Override synchronized void add(E value); @Override E get(int index); synchronized E pollFirst(); synchronized E pollLast(); @Override synchronized Iterator<E> iterator(); }### Answer: @Test public void ifCollectionAreVoidThenHasNextWillReturnFalse() { SimpleList<Integer> testList = new SimpleLinkedList<>(); Iterator<Integer> testIterator = testList.iterator(); assertThat(testIterator.hasNext(), is(false)); }
### Question: Character implements Runnable { public SimpleBlockingQueue<Cell> getOutput() { return this.output; } Character(Board currentBoard, Cell currentCell, SimpleBlockingQueue<Cell> moves); SimpleBlockingQueue<Cell> getOutput(); @Override void run(); }### Answer: @Test public void ifMoveTheCharacterItWillMove() { Board testBoard = new Board(10); testBoard.init(0); SimpleBlockingQueue<Cell> moves = new SimpleBlockingQueue<>(); moves.offer(new Cell(1, 1)); moves.offer(new Cell(1, 1)); Character character = new Character(testBoard, new Cell(1, 1), moves); SimpleBlockingQueue<Cell> output = character.getOutput(); Thread first = new Thread(character); first.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } first.interrupt(); try { first.join(); } catch (InterruptedException e) { first.interrupt(); } ArrayList<Cell> result = new ArrayList<>(); result.add(output.poll()); result.add(output.poll()); result.add(output.poll()); assertThat(result, is(new ArrayList<>(asList(new Cell(2, 2), new Cell(3, 3), new Cell(3, 3))))); }
### Question: Game { public void startGame(int difficultLevel) { this.board.init(difficultLevel); int rowPosition = 0; int columnPosition = 0; int userNumbers = 0; for (int i = 0; i < this.randomInputCharacters + this.inputsPlayers.size(); i++) { if (columnPosition >= this.board.getSize()) { rowPosition++; columnPosition = 0; } if (i < this.randomInputCharacters) { SimpleBlockingQueue<Cell> input = new SimpleBlockingQueue<>(); this.allThreads[threadPosition] = new Thread( new Character(this.board, new Cell(rowPosition, columnPosition++), input) ); this.allThreads[threadPosition++].start(); this.allThreads[threadPosition] = new Thread(new RandomInput(input, 1000)); this.allThreads[threadPosition++].start(); } else { this.allThreads[threadPosition] = new Thread( new Character(this.board, new Cell( rowPosition, columnPosition++), this.inputsPlayers.get(userNumbers++) ) ); this.allThreads[threadPosition++].start(); } } } Game(int boardSize, int randomInputCharacters, List<SimpleBlockingQueue<Cell>> inputsPlayers); void startGame(int difficultLevel); void stopGame(); }### Answer: @Test public void startGame() { List<SimpleBlockingQueue<Cell>> userInputs = new ArrayList<>(); SimpleBlockingQueue<Cell> testUserInput = new SimpleBlockingQueue<>(); userInputs.add(testUserInput); new Thread(new RandomInput(testUserInput, 200)).start(); Game testGame = new Game(10, 2, userInputs); testGame.startGame(1); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } testGame.stopGame(); }
### Question: SimpleHashSet implements Iterable<E> { @Override public Iterator<E> iterator() { return new Iterator<E>() { private int position; private final int expectedModCount = modCount; { position = -1; position = findNextNotNullElement(); } private int findNextNotNullElement() { int result = -1; for (int i = position + 1; i < mainStorage.length; i++) { if (mainStorage[i] != null) { result = i; break; } } return result; } @Override public boolean hasNext() { return (this.position != -1); } @Override public E next() { if (this.expectedModCount != modCount) { throw new ConcurrentModificationException(); } if (!hasNext()) { throw new NoSuchElementException(); } E result = (E) mainStorage[this.position]; this.position = findNextNotNullElement(); return result; } }; } SimpleHashSet(); SimpleHashSet(int size); int getSize(); boolean add(E element); boolean contains(E element); boolean remove(E element); @Override Iterator<E> iterator(); }### Answer: @Test(expected = NoSuchElementException.class) public void ifNoElementThenNoSuchElementException() { SimpleHashSet<Integer> testSet = new SimpleHashSet<>(10); Iterator<Integer> testIterator = testSet.iterator(); assertThat(testIterator.hasNext(), is(false)); testIterator.next(); }
### Question: PrimeIterator implements Iterator { @Override public boolean hasNext() { return findNextPrimeNumber() != -1; } PrimeIterator(int[] array); @Override boolean hasNext(); @Override Object next(); @Override void remove(); }### Answer: @Test public void shouldReturnFalseCauseThereIsNoAnyPrimeNumber() { it = new PrimeIterator(new int[]{4, 6}); assertThat("should return false, cause there is no any prime number", it.hasNext(), is(false)); }
### Question: DepartmentsSort { public TreeSet<String> reverseOrderSort(String[] departments) { TreeSet<String> sortedDepartments = new TreeSet<>(Comparator.reverseOrder()); sortedDepartments.addAll(naturalOrderSort(departments)); return sortedDepartments; } Set<String> naturalOrderSort(String[] departments); TreeSet<String> reverseOrderSort(String[] departments); }### Answer: @Test public void ifArrayReversOrderSortingThenResultIsReversOrderSortingExpect() { DepartmentsSort testSort = new DepartmentsSort(); Set<String> result = testSort.reverseOrderSort(arrayForSorting); assertThat(result, is(new LinkedHashSet<>(asList(reversOrderSortingExpect)))); }
### Question: EvenIterator implements Iterator { @Override public boolean hasNext() { return (this.position != -1); } EvenIterator(int[] array); @Override boolean hasNext(); @Override Object next(); @Override void remove(); }### Answer: @Test public void shouldReturnFalseIfNoAnyEvenNumbers() { it = new EvenIterator(new int[]{1}); assertThat(it.hasNext(), is(false)); }
### Question: OrderBook implements Comparable { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderBook orderBook = (OrderBook) o; return id == orderBook.id; } OrderBook(int id, String book, String type, String action, double price, int volume); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(Object o); int getId(); String getBook(); String getType(); String getAction(); double getPrice(); int getVolume(); }### Answer: @Test public void ifIdEqualsThenOrdersShouldBeEquals() { OrderBook test1 = new OrderBook(1, "gazprom", "delete", "bid", 10, 100); OrderBook test2 = new OrderBook(1, "gazprom", "add", "bid", 10, 100); assertThat(test1.equals(test2), is(true)); }
### Question: SimpleArray implements Iterable<T> { @Override public Iterator<T> iterator() { return new Iterator<T>() { private int position = 0; @Override public boolean hasNext() { return this.position < size(); } @Override public T next() { if (this.position >= size()) { throw new NoSuchElementException(); } return get(position++); } }; } SimpleArray(); SimpleArray(int size); int size(); void add(T model); void set(int index, T model); void delete(int index); T get(int index); @Override Iterator<T> iterator(); }### Answer: @Test public void iterator() { SimpleArray<Integer> testArray = new SimpleArray<>(); Iterator<Integer> it = testArray.iterator(); testArray.add(1); testArray.add(2); testArray.add(3); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(1)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(3)); assertThat(it.hasNext(), is(false)); }
### Question: SimpleHashMap implements Iterable<SimpleHashMap.Entry<K, V>> { @Override public Iterator<Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private final int expectedModCount = modCount; private int position; private int findNextNotNullElement() { int result = -1; for (int i = this.position; i < mainStorage.length; i++) { if (mainStorage[i] != null) { result = i; break; } } return result; } @Override public boolean hasNext() { return (findNextNotNullElement() != -1); } @Override public Entry<K, V> next() { if (this.expectedModCount != modCount) { throw new ConcurrentModificationException(); } if (!hasNext()) { throw new NoSuchElementException(); } int nextNotNullElementIndex = findNextNotNullElement(); Entry<K, V> result = mainStorage[findNextNotNullElement()]; this.position = nextNotNullElementIndex + 1; return result; } }; } SimpleHashMap(); SimpleHashMap(int size); int getSize(); boolean insert(K key, V value); V get(K key); boolean delete(K key); @Override Iterator<Entry<K, V>> iterator(); }### Answer: @Test(expected = NoSuchElementException.class) public void ifMapIsEmptyThenIteratorNextThrowNoSuchElementException() { Iterator<SimpleHashMap.Entry<User, String>> testIterator = testMap.iterator(); assertThat(testIterator.hasNext(), is(false)); testIterator.next(); }
### Question: Anagrams { public boolean checkWords(String first, String second) { boolean result = true; if (first.length() != second.length()) { result = false; } else { HashMap<Character, Integer> symbolStorage = new HashMap<>(); for (Character symbol : first.toLowerCase().toCharArray()) { Integer symbolCounter = symbolStorage.putIfAbsent(symbol, 1); if (symbolCounter != null) { symbolStorage.put(symbol, symbolCounter + 1); } } for (Character symbol : second.toLowerCase().toCharArray()) { Integer currentValue = symbolStorage.get(symbol); if (currentValue == null) { result = false; break; } if (currentValue > 1) { symbolStorage.replace(symbol, currentValue - 1); } else { symbolStorage.remove(symbol); } } } return result; } boolean checkWords(String first, String second); }### Answer: @Test public void ifTwoWordsAreAnagramsThenCheckShouldReturnTrue() { Anagrams testAnagrams = new Anagrams(); Boolean result = testAnagrams.checkWords("мама", "амам"); assertThat(result, is(true)); } @Test public void ifTwoWordsAreNotAnagramsThenCheckShouldReturnFalse() { Anagrams testAnagrams = new Anagrams(); assertThat(testAnagrams.checkWords("мама", "папа"), is(false)); } @Test public void ifDifferentNumberOfIdenticalLettersCheckShouldReturnFalse() { Anagrams testAnagrams = new Anagrams(); assertThat(testAnagrams.checkWords("мама", "мааа"), is(false)); } @Test public void ifFirstWordIsLongerThenSecondCheckShouldReturnFalse() { Anagrams testAnagrams = new Anagrams(); assertThat(testAnagrams.checkWords("мамаа", "мама"), is(false)); } @Test public void ifAnagramsHasADifferentCaseCheckShouldReturnTrue() { assertThat(new Anagrams().checkWords("Мама", "мама"), is(true)); }
### Question: StringsCompare implements Comparator<String> { @Override public int compare(String left, String right) { for (int i = 0; i < Math.min(left.length(), right.length()); i++) { if (left.charAt(i) != right.charAt(i)) { return left.charAt(i) - right.charAt(i); } } return left.length() - right.length(); } @Override int compare(String left, String right); }### Answer: @Test public void whenStringsAreEqualThenZero() { StringsCompare compare = new StringsCompare(); int rst = compare.compare( "Ivanov", "Ivanov" ); assertThat(rst, is(0)); } @Test public void whenLeftLessThanRightResultShouldBeNegative() { StringsCompare compare = new StringsCompare(); int rst = compare.compare( "Ivanov", "Ivanova" ); assertThat(rst, lessThan(0)); } @Test public void whenLeftGreaterThanRightResultShouldBePositive() { StringsCompare compare = new StringsCompare(); int rst = compare.compare( "Petrov", "Ivanova" ); assertThat(rst, greaterThan(0)); } @Test public void secondCharOfLeftLessThanRightShouldBeNegative() { StringsCompare compare = new StringsCompare(); int rst = compare.compare( "Patrova", "Petrov" ); assertThat(rst, lessThan(0)); }
### Question: UserStorage { public int add(User user) { return this.storage.add(user); } UserStorage(Storage storage); int add(User user); User findById(int id); }### Answer: @Test public void add() { Storage memory = new MemoryStorage(); UserStorage storage = new UserStorage(memory); storage.add(new User()); } @Test public void whenLoadContextShouldGetUserStorageBean() { UserStorage memory = this.context.getBean("storage", UserStorage.class); memory.add(new User()); assertNotNull(memory); } @Test public void whenLoadContextShouldGetJdbcStorageBean() { UserStorage memory = this.context.getBean("jdbcStorage", UserStorage.class); memory.add(new User()); assertNotNull(memory); }
### Question: JobPicker { public void start() { this.timer.schedule(new ParseTask(), this.delay, this.period); } JobPicker(int delay, int period); JobPicker(); void start(); void stop(); }### Answer: @Ignore @Test public void jobPickerT() { JobPicker test = new JobPicker(); test.start(); try { Thread.sleep(50000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("finish"); }
### Question: Vacancy { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Vacancy vacancy = (Vacancy) o; return Objects.equals(text, vacancy.text) && Objects.equals(url, vacancy.url) && Objects.equals(date, vacancy.date); } Vacancy(); Vacancy(String text, String url, Calendar date); @Override boolean equals(Object o); @Override int hashCode(); boolean isFull(); String getText(); void setText(String text); String getUrl(); void setUrl(String url); Calendar getDate(); void setDate(Calendar date); }### Answer: @Test public void ifVacancyAreEqualsThenEqualsShouldBeReturnTrue() { Vacancy first = new Vacancy("test", "test", new GregorianCalendar(0, 0, 0)); Vacancy second = new Vacancy("test", "test", new GregorianCalendar(0, 0, 0)); assertThat(first.equals(second), is(true)); assertThat(second.equals(first), is(true)); } @Test public void ifVacancyDifferenceThenEqualsShouldBeReturnFalse() { Vacancy first = new Vacancy("test", "test", new GregorianCalendar(0, 0, 0)); Vacancy second = new Vacancy("test", "tes", new GregorianCalendar(1, 0, 0)); assertThat(first.equals(second), is(false)); assertThat(second.equals(first), is(false)); }
### Question: ConvertXSQT { public void convert(File source, File dest, File scheme) { TransformerFactory factory = TransformerFactory.newInstance(); try { Transformer transformer = factory.newTransformer(new StreamSource(scheme)); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http: transformer.transform(new StreamSource(source), new StreamResult(dest)); } catch (TransformerException e) { e.printStackTrace(); } } void convert(File source, File dest, File scheme); }### Answer: @Test public void testConvert() { ConvertXSQT converter = new ConvertXSQT(); File source = new File(getClass().getClassLoader().getResource("ConvertXSQTtestSource.xml").getFile()); File dest = new File(getClass().getClassLoader().getResource("ConvertXSQTtestDest.xml").getFile()); File scheme = new File(getClass().getClassLoader().getResource("scheme.xsl").getFile()); converter.convert(source, dest, scheme); StringBuilder result = new StringBuilder(); try (Scanner scan = new Scanner(dest)) { while (scan.hasNext()) { result.append(scan.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entries>" + " <entry field=\"0\"/>" + " <entry field=\"1\"/>" + "</entries>"; assertThat(result.toString(), is(expect)); }
### Question: ParseCounter { public int getSum(File file) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(file, new Parser()); } catch (SAXException | IOException | ParserConfigurationException e) { e.printStackTrace(); } LOGGER.info("this.counter"); return this.counter; } int getSum(File file); }### Answer: @Test public void getSum() { ParseCounter testCounter = new ParseCounter(); int result = testCounter.getSum( new File(getClass().getClassLoader().getResource("ParseCounterTestSource.xml").getFile()) ); assertThat(result, is(28)); }
### Question: StoreXML { void save(List<Entry> list) { JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(Entries.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(new Entries(list), this.target); } catch (JAXBException e) { e.printStackTrace(); } } StoreXML(File target); }### Answer: @Test public void testSave() { List<StoreXML.Entry> inputData = new ArrayList<>(); for (int i = 0; i < 2; i++) { inputData.add(new StoreXML.Entry(i)); } File target = new File(getClass().getClassLoader().getResource("StoreXMLTest.xml").getFile()); StoreXML testStore = new StoreXML(target); testStore.save(inputData); StringBuilder result = new StringBuilder(); try (Scanner scanner = new Scanner(target)) { while (scanner.hasNext()) { result.append(scanner.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } StringBuilder expect = new StringBuilder(); expect .append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") .append("<entries>") .append(" <entry>") .append(" <field>0</field>") .append(" </entry>") .append(" <entry>") .append(" <field>1</field>") .append(" </entry>") .append("</entries>"); assertThat(result.toString(), is(expect.toString())); }
### Question: UserDao extends CrudDAO<User> { public User findUserByLogin(String login) { return getWrapper().wrapAndExecute(session -> { User result = null; try { result = session.createQuery("from User where login = :login", User.class) .setParameter("login", login).getSingleResult(); } catch (Exception e) { LOG.error(e.getMessage(), e); } return result; } ); } UserDao(SessionFactory sf); User findUserByLogin(String login); }### Answer: @Test public void findUserByLogin() { User expect = new User(); expect.setLogin("testLogin10"); expect.setPassword("testPassword10"); this.getTestDao().add(expect); assertThat(this.getTestDao().findUserByLogin(expect.getLogin()).getPassword(), is(expect.getPassword())); }
### Question: CrudDAO { public int add(T entity) { return this.wrapper.wrapAndExecute(session -> { session.save(entity); return entity.getId(); }); } CrudDAO(SessionFactory sf); int add(T entity); void delete(T entity); void update(T entity); @SuppressWarnings("unchecked") T findById(int id); @SuppressWarnings("unchecked") List<T> findAll(); }### Answer: @Test public void add() { int entityId = this.getTestDao().add(this.getTestEntity()); T resultEntity = this.getTestDao().findById(entityId); resultEntity.setId(0); assertThat(resultEntity, is(this.getTestEntity())); }
### Question: CrudDAO { public void delete(T entity) { this.wrapper.wrapAndExecute(session -> { session.delete(entity); return null; }); } CrudDAO(SessionFactory sf); int add(T entity); void delete(T entity); void update(T entity); @SuppressWarnings("unchecked") T findById(int id); @SuppressWarnings("unchecked") List<T> findAll(); }### Answer: @Test public void delete() { int entityId = this.getTestDao().add(this.getTestEntity()); T entity = this.getTestEntity(); entity.setId(entityId); this.getTestDao().delete(entity); assertNull(this.getTestDao().findById(entityId)); }
### Question: CrudDAO { public void update(T entity) { this.wrapper.wrapAndExecute(session -> { session.update(entity); return null; }); } CrudDAO(SessionFactory sf); int add(T entity); void delete(T entity); void update(T entity); @SuppressWarnings("unchecked") T findById(int id); @SuppressWarnings("unchecked") List<T> findAll(); }### Answer: @Test public void update() { int entityId = this.getTestDao().add(this.getTestEntity()); T upEntity = this.getSecondTestEntity(); upEntity.setId(entityId); this.getTestDao().update(upEntity); assertThat(this.getTestDao().findById(entityId), is(upEntity)); }
### Question: Board { public Cell[] checkWay(Cell source, Cell dest) throws FigureNotFoundException, ImpossibleMoveException { Cell[] figureWay = {new Cell(-1, -1)}; if (source != null && dest != null) { boolean doneFigureFound = false; for (Figure checkedFigure : figures) { if (checkedFigure != null && checkedFigure.position != null && checkedFigure.position.equals(source)) { figureWay = checkedFigure.way(source, dest); doneFigureFound = true; break; } } if (!doneFigureFound) { throw new FigureNotFoundException(String.format( "%s: %s | %s %s", "В ячейке", source.getX(), source.getY(), "нет фигуры.") ); } } return figureWay; } void add(Figure figure); Figure[] getFigures(); Cell[] checkWay(Cell source, Cell dest); boolean checkFigureWay(Cell[] way); }### Answer: @Test public void checkWayIfFigureNotFoundInFiguresThenThrowException() throws ImpossibleMoveException { Board testBoard = new Board(); try { testBoard.checkWay(new Cell(4, 4), new Cell(2, 2)); } catch (FigureNotFoundException fnfe) { assertThat(fnfe.getMessage(), is("В ячейке: 4 | 4 нет фигуры.")); } }
### Question: Pawn extends Figure { public Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException { int differenceX = Math.abs(dest.getX() - source.getX()); boolean sourceXEqualTwo = source.getX() == 2; boolean doneDependingPosition = (sourceXEqualTwo ? differenceX == 2 || differenceX == 1 : differenceX == 1); if (dest.getX() < 0 && dest.getX() > 9 && dest.getY() != source.getY() && !doneDependingPosition) { throw new ImpossibleMoveException("Пешка так не ходит"); } Cell[] result; if (sourceXEqualTwo && differenceX == 2) { result = new Cell[]{new Cell(source.getX() + 1, source.getY()), dest}; } else { result = new Cell[]{dest}; } return result; } Pawn(Cell position); Cell[] way(Cell source, Cell dest); Figure copy(Cell dest); }### Answer: @Test public void ifPawnGoingFromPointTwoTwoToPointFourTwo() throws ImpossibleMoveException { Pawn testPawn = new Pawn(new Cell(2, 2)); Cell[] result = testPawn.way(new Cell(2, 2), new Cell(4, 2)); assertThat(result, is(new Cell[]{new Cell(3, 2), new Cell(4, 2)})); } @Test public void ifPawnGoingFromPointThreeTwoToPointFourTwo() throws ImpossibleMoveException { Pawn testPawn = new Pawn(new Cell(3, 2)); Cell[] result = testPawn.way(new Cell(3, 2), new Cell(4, 2)); assertThat(result, is(new Cell[]{new Cell(4, 2)})); } @Test public void ifWrongWayThenReturnImeException() { Pawn testPawn = new Pawn(new Cell(4, 4)); try { testPawn.way(new Cell(4, 4), new Cell(6, 4)); } catch (ImpossibleMoveException ime) { assertThat("Пешка так не ходит", is(ime.getMessage())); } }
### Question: SortUser { public Set<User> sort(List<User> list) { return new TreeSet<>(list); } Set<User> sort(List<User> list); List<User> sortNameLength(List<User> list); List<User> sortByAllFields(List<User> list); }### Answer: @Test public void ifSortUserListThenReturnTreeMapWithSortingUsersById() { User first = new User("Egor", 1); User second = new User("Oleg", 2); User third = new User("Ivan", 3); SortUser testSort = new SortUser(); Set<User> result = testSort.sort(new ArrayList<>(asList(first, third, second))); Set<User> expect = new LinkedHashSet<>(asList(first, second, third)); assertThat(result, is(expect)); }
### Question: Paint { public void draw(Shape shape) { System.out.println(shape.draw()); } void draw(Shape shape); }### Answer: @Test public void whenDrawSquare() { new Paint().draw(new Square()); assertThat( new String(out.toByteArray()), is( new StringBuilder() .append("†††††††††") .append("† †") .append("† †") .append("†††††††††" + ln) .toString() ) ); } @Test public void whenDrawTriangle() { new Paint().draw(new Triangle()); assertThat( new String(out.toByteArray()), is( new StringBuilder() .append(" † ") .append(" ††† ") .append(" †††††† ") .append("†††††††††" + ln) .toString() ) ); }
### Question: Square implements Shape { public String draw() { StringBuilder pic = new StringBuilder(); pic.append("†††††††††"); pic.append("† †"); pic.append("† †"); pic.append("†††††††††"); return pic.toString(); } String draw(); }### Answer: @Test public void whenDrawSquare() { Square square = new Square(); assertThat( square.draw(), is( new StringBuilder() .append("†††††††††") .append("† †") .append("† †") .append("†††††††††") .toString() ) ); }
### Question: Triangle implements Shape { public String draw() { StringBuilder pic = new StringBuilder(); pic.append(" † "); pic.append(" ††† "); pic.append(" †††††† "); pic.append("†††††††††"); return pic.toString(); } String draw(); }### Answer: @Test public void whenDrawSquare() { Triangle triangle = new Triangle(); assertThat( triangle.draw(), is( new StringBuilder() .append(" † ") .append(" ††† ") .append(" †††††† ") .append("†††††††††") .toString() ) ); }
### Question: ValidateInput implements Input { @Override public String ask(String question) { return this.input.ask(question); } ValidateInput(final Input input); @Override String ask(String question); int ask(String question, List<Integer> range); }### Answer: @Test public void whenInvalidInput() { ValidateInput input = new ValidateInput( new StubInput(new String[] {"invalid", "1"}) ); input.ask("Enter", new ArrayList<>(Collections.singleton(1))); assertThat( this.mem.toString(), is( String.format("Please, enter validate data again.%n") ) ); }
### Question: SortUser { public List<User> sortNameLength(List<User> list) { list.sort( new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getName().length() - o2.getName().length(); } } ); return list; } Set<User> sort(List<User> list); List<User> sortNameLength(List<User> list); List<User> sortByAllFields(List<User> list); }### Answer: @Test public void ifSortUsersListByNameLengthThenReturnSortedList() { User first = new User("Egor", 10); User second = new User("Roman", 25); User third = new User("Vasiliy", 20); SortUser testSort = new SortUser(); List<User> result = testSort.sortNameLength(new ArrayList<>(asList(first, third, second))); List<User> expect = new ArrayList<>(asList(first, second, third)); assertThat(result, is(expect)); }
### Question: Doctor extends Profession { public String threat(Patient patient) { return this.profession + " " + this.name + " threat " + patient.name; } Doctor(String name); String threat(Patient patient); Diagnose heal(Patient patient); void diagnosed(Patient patient, String disease, int duration, String treatment); }### Answer: @Test public void ifDocThreatPitThenReturnDoctorBobThreatPit() { String expect = "Doctor Bob threat Pit"; String result = doc.threat(pit); assertThat(result, is(expect)); }
### Question: Doctor extends Profession { public Diagnose heal(Patient patient) { return patient.diagnose; } Doctor(String name); String threat(Patient patient); Diagnose heal(Patient patient); void diagnosed(Patient patient, String disease, int duration, String treatment); }### Answer: @Test public void ifDocHealPitThenPitReturnDiagnose() { Diagnose diagnose = new Diagnose("plague", 30, "nothing"); pit.diagnose = diagnose; Diagnose result = doc.heal(pit); assertThat(result, is(diagnose)); }
### Question: Doctor extends Profession { public void diagnosed(Patient patient, String disease, int duration, String treatment) { patient.diagnose = new Diagnose(disease, duration, treatment); } Doctor(String name); String threat(Patient patient); Diagnose heal(Patient patient); void diagnosed(Patient patient, String disease, int duration, String treatment); }### Answer: @Test public void ifDocDiagnosedPitThenPitDiagnosWasDiagnosed() { doc.diagnosed(pit, "plague", 30, "nothing"); String result = pit.diagnose.disease + " " + pit.diagnose.duration + " " + pit.diagnose.treatment; String expect = "plague 30 nothing"; assertThat(result, is(expect)); }
### Question: Engineer extends Profession { public String build(House house) { return this.profession + " " + this.name + " build " + house.address; } Engineer(String name); String build(House house); }### Answer: @Test public void ifEngineerBuildHouseThenReturnEngineerBillBuildHOuseAdres() { Engineer bill = new Engineer("Bill"); House home = new House("Moscovscaya 34"); assertThat(bill.build(home), is("Engineer Bill build Moscovscaya 34")); }
### Question: Teacher extends Profession { public String teach(Student student) { return this.profession + " " + this.name + " teach student " + student.name; } Teacher(String name); String teach(Student student); }### Answer: @Test public void ifTeacherTeachStudenThenReturnStringTeacherOlegTeachStudentIvan() { Teacher oleg = new Teacher("Oleg"); Student ivan = new Student("Ivan"); assertThat(oleg.teach(ivan), is("Teacher Oleg teach student Ivan")); }
### Question: SortUser { public List<User> sortByAllFields(List<User> list) { list.sort( new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getName().equals(o2.getName()) ? o1.getAge() - o2.getAge() : o1.getName().compareTo(o2.getName()); } } ); return list; } Set<User> sort(List<User> list); List<User> sortNameLength(List<User> list); List<User> sortByAllFields(List<User> list); }### Answer: @Test public void ifSortUserListByAllFieldsThenReturnSortedList() { User first = new User("Egor", 10); User second = new User("Roman", 25); User third = new User("Egor", 20); SortUser testSort = new SortUser(); List<User> result = testSort.sortByAllFields(new ArrayList<>(asList(first, second, third))); List<User> expect = new ArrayList<>(asList(first, third, second)); assertThat(result, is(expect)); }
### Question: DbStore implements Store, UserAddressStore { public static DbStore getInstance() { return INSTANCE; } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer: @Test public void getInstance() { assertThat(this.testStore, is(DbStore.getInstance())); }
### Question: DbStore implements Store, UserAddressStore { @Override public void add(User user) { try (Connection connect = SOURCE.getConnection(); PreparedStatement st = connect.prepareStatement( PROPS.getProperty("addUser") )) { st.setString(1, user.getName()); st.setString(2, user.getLogin()); st.setString(3, user.getEmail()); st.setTimestamp(4, new Timestamp(user.getCreateDate().getTimeInMillis())); st.setString(5, user.getPassword()); st.setString(6, user.getRole()); st.setString(7, user.getCity()); st.execute(); } catch (SQLException e) { LOG.error(e.getMessage(), e); } } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer: @Test public void add() throws SQLException { this.testStore.add(this.first); try (Statement st = this.connect.createStatement(); ResultSet rstSet = st.executeQuery("SELECT * FROM users WHERE name = 'test'")) { rstSet.next(); assertThat(rstSet.getString("name"), is("test")); assertThat(rstSet.getString("login"), is("test")); assertThat(rstSet.getString("email"), is("test")); assertThat(rstSet.getInt("id") > 0, is(true)); assertThat(rstSet.next(), is(false)); } }
### Question: DbStore implements Store, UserAddressStore { @Override public void update(User newUser) { try (Connection con = SOURCE.getConnection(); PreparedStatement st = con.prepareStatement( PROPS.getProperty("updateUser") )) { st.setString(1, newUser.getName()); st.setString(2, newUser.getLogin()); st.setString(3, newUser.getEmail()); st.setString(4, newUser.getPassword()); st.setString(5, newUser.getRole()); st.setString(6, newUser.getCity()); st.setInt(7, newUser.getId()); st.execute(); } catch (SQLException e) { LOG.error(e.getMessage(), e); } } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer: @Test public void update() throws SQLException { int userId = 0; try (Statement st = this.connect.createStatement()) { st.execute("INSERT INTO users (name, login, email) VALUES ('up', 'up', 'up')"); try (ResultSet rstSet = st.executeQuery("SELECT id FROM users WHERE name = 'up'")) { rstSet.next(); userId = rstSet.getInt("id"); } User userUpdated = new User("test", "test", "test", "user", "test"); userUpdated.setId(userId); this.testStore.update(userUpdated); try (ResultSet rstSet = st.executeQuery("SELECT name, login, email FROM users WHERE id =" + userId)) { assertThat(rstSet.next(), is(true)); assertThat(rstSet.getString("name"), is("test")); assertThat(rstSet.getString("login"), is("test")); assertThat(rstSet.getString("email"), is("test")); assertThat(rstSet.next(), is(false)); } } }
### Question: DbStore implements Store, UserAddressStore { @Override public void delete(int userId) { try (Connection con = SOURCE.getConnection(); PreparedStatement st = con.prepareStatement( PROPS.getProperty("deleteUser") )) { st.setInt(1, userId); st.execute(); } catch (SQLException e) { LOG.error(e.getMessage(), e); } } private DbStore(); static DbStore getInstance(); @Override User findByLogin(String login); @Override void add(User user); @Override void update(User newUser); @Override void delete(int userId); @Override List<User> findAll(); @Override User findById(int id); List<String> findAllCountries(); List<String> findCitiesByCountry(String name); }### Answer: @Test public void delete() throws SQLException { int userId = 0; try (Statement st = this.connect.createStatement()) { st.execute("INSERT INTO users (name, login, email) VALUES ('test', 'test', 'test')"); try (ResultSet rstSet = st.executeQuery("SELECT id FROM users WHERE name = 'test'")) { rstSet.next(); userId = rstSet.getInt("id"); } this.testStore.delete(userId); try (ResultSet rstSet = st.executeQuery("SELECT * FROM users WHERE name = 'test'")) { assertThat(rstSet.next(), is(false)); } } }
### Question: ConvertList { public List<Integer> toList(int[][] array) { ArrayList<Integer> result = new ArrayList<>(array[0].length + array[1].length); for (int[] currentArr : array) { for (int value : currentArr) { result.add(value); } } return result; } List<Integer> toList(int[][] array); int[][] toArray(List<Integer> list, int rows); List<Integer> convert(List<int[]> list); }### Answer: @Test public void convertTwoDimensionalArrayToArrayList() { ConvertList testConvert = new ConvertList(); List<Integer> result = testConvert.toList(new int[][]{ {1, 2, 3}, {4, 5, 6}, {7, 8, 8} }); List<Integer> expect = new ArrayList<>(asList(1, 2, 3, 4, 5, 6, 7, 8, 8)); assertThat(result, is(expect)); }
### Question: JavaInterfaceBuilderImpl extends BaseBuilder implements JavaInterfaceBuilder { @Override public void setJavaDoc(String comment) { if (StringUtils.isNotEmpty(comment)) { declaration.setJavadocComment( JavadocUtils.createJavadocComment(comment, INDENTATION_NO_INDENTATION)); } } JavaInterfaceBuilderImpl(String packageName, String name, String annotationsPackage); static void main(String[] args); @Override void setJavaDoc(String comment); @Override void addAnnotation(String annotationName); @Override void addMethodAnnotation(String methodName, String annotationName); @Override void addParametrizedMethodAnnotation( String methodName, String annotationName, String parameter); @Override String getName(); @Override void addImport(String packageName, String object); @Override void addMethod( String name, String description, List<MethodParam> methodParams, String returnType); }### Answer: @Test public void testBasicInterface() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture)); interfaceBuilder.setJavaDoc(""); replayAll(); interfaceBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "public interface InterfaceTest {\n" + "}\n" + "", compilationUnitCapture.getValue().toString()); verifyAll(); } @Test public void testSetJavadoc() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture)); interfaceBuilder.setJavaDoc("Java doc."); replayAll(); interfaceBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "\n" + "public interface InterfaceTest {\n" + "}\n", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: ChromeDevToolsUtils { public static <T> void waitForEvent(Function<EventHandler<T>, EventListener> eventConsumer) { final CountDownLatch countDownLatch = new CountDownLatch(1); final EventListener eventListener = eventConsumer.apply( event -> { countDownLatch.countDown(); }); try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for event.", e); } finally { eventListener.unsubscribe(); } } static void closeQuietly(Closeable closeable); static void waitForEvent(Function<EventHandler<T>, EventListener> eventConsumer); }### Answer: @Test public void testWaitForEvent() { EventListener eventListener = mock(EventListener.class); eventListener.unsubscribe(); replay(eventListener); ChromeDevToolsUtils.waitForEvent( eventHandler -> { eventHandler.onEvent(null); return eventListener; }); verify(eventListener); }
### Question: ChromeLauncher implements AutoCloseable { public boolean isAlive() { return chromeProcess != null && chromeProcess.isAlive(); } ChromeLauncher(); ChromeLauncher(ChromeLauncherConfiguration configuration); ChromeLauncher( ProcessLauncher processLauncher, Environment environment, ShutdownHookRegistry shutdownHookRegistry, ChromeLauncherConfiguration configuration); ChromeService launch(Path chromeBinaryPath, ChromeArguments chromeArguments); ChromeService launch(ChromeArguments chromeArguments); ChromeService launch(boolean headless); ChromeService launch(); Path getChromeBinaryPath(); @Override void close(); int exitValue(); boolean isAlive(); static final String ENV_CHROME_PATH; }### Answer: @Test public void testIsAlive() throws IOException { assertFalse(launcher.isAlive()); final Path binaryPath = Paths.get("test-binary-path"); final ChromeArguments chromeArguments = ChromeArguments.builder().incognito().userDataDir("user-data-dir-param").build(); shutdownHookRegistry.register(anyObject()); final String trigger = "\r\n\r\nDevTools listening on ws: expect(process.getInputStream()).andReturn(new ByteArrayInputStream(trigger.getBytes())); expect(process.isAlive()).andReturn(true); Capture<List<String>> captureArguments = Capture.newInstance(); expect(processLauncher.launch(eq("test-binary-path"), capture(captureArguments))) .andReturn(process); replayAll(); launcher.launch(binaryPath, chromeArguments); assertTrue(launcher.isAlive()); verifyAll(); }
### Question: ChromeLauncher implements AutoCloseable { public int exitValue() { if (chromeProcess == null) { throw new IllegalStateException("Chrome process has not been started started."); } return chromeProcess.exitValue(); } ChromeLauncher(); ChromeLauncher(ChromeLauncherConfiguration configuration); ChromeLauncher( ProcessLauncher processLauncher, Environment environment, ShutdownHookRegistry shutdownHookRegistry, ChromeLauncherConfiguration configuration); ChromeService launch(Path chromeBinaryPath, ChromeArguments chromeArguments); ChromeService launch(ChromeArguments chromeArguments); ChromeService launch(boolean headless); ChromeService launch(); Path getChromeBinaryPath(); @Override void close(); int exitValue(); boolean isAlive(); static final String ENV_CHROME_PATH; }### Answer: @Test(expected = IllegalStateException.class) public void testExitValueThrowsExceptionWhenProcessNotStarted() throws IOException { launcher.exitValue(); } @Test public void testExitValue() throws IOException { final Path binaryPath = Paths.get("test-binary-path"); final ChromeArguments chromeArguments = ChromeArguments.builder().incognito().userDataDir("user-data-dir-param").build(); shutdownHookRegistry.register(anyObject()); final String trigger = "\r\n\r\nDevTools listening on ws: expect(process.getInputStream()).andReturn(new ByteArrayInputStream(trigger.getBytes())); expect(process.exitValue()).andReturn(123); Capture<List<String>> captureArguments = Capture.newInstance(); expect(processLauncher.launch(eq("test-binary-path"), capture(captureArguments))) .andReturn(process); replayAll(); launcher.launch(binaryPath, chromeArguments); assertEquals(123, launcher.exitValue()); verifyAll(); }
### Question: ChromeArguments { public static Builder builder() { return new Builder(); } Boolean getHeadless(); Map<String, Object> getAdditionalArguments(); Boolean getNoDefaultBrowserCheck(); Boolean getNoFirstRun(); String getUserDataDir(); Integer getRemoteDebuggingPort(); Boolean getIncognito(); Boolean getDisableGpu(); Boolean getHideScrollbars(); Boolean getMuteAudio(); Boolean getDisableBackgroundNetworking(); Boolean getDisableBackgroundTimerThrottling(); Boolean getDisableClientSidePhishingDetection(); Boolean getDisableDefaultApps(); Boolean getDisableExtensions(); Boolean getDisableHangMonitor(); Boolean getDisablePopupBlocking(); Boolean getDisablePromptOnRepost(); Boolean getDisableSync(); Boolean getDisableTranslate(); Boolean getMetricsRecordingOnly(); Boolean getSafebrowsingDisableAutoUpdate(); static Builder builder(); static Builder defaults(boolean headless); static final String USER_DATA_DIR_ARGUMENT; }### Answer: @Test public void testBuilder() { assertNotNull(ChromeArguments.builder()); }
### Question: SourceProjectImpl implements SourceProject { @Override public void saveAll() { PrettyPrinterConfiguration prettyPrinterConfiguration = new PrettyPrinterConfiguration(); prettyPrinterConfiguration.setIndent("\t"); prettyPrinterConfiguration.setPrintComments(true); prettyPrinterConfiguration.setPrintJavadoc(true); prettyPrinterConfiguration.setOrderImports(true); PrettyPrinter prettyPrinter = new PrettyPrinter(prettyPrinterConfiguration); JavaFormatterOptions javaFormatterOptions = JavaFormatterOptions.builder().style(JavaFormatterOptions.Style.GOOGLE).build(); sourceRoot.setPrinter(googleCodeFormatter(javaFormatterOptions, prettyPrinter::print)); sourceRoot.saveAll(sourceRoot.getRoot()); } SourceProjectImpl(Path outputLocation); SourceProjectImpl(SourceRoot sourceRoot); @Override void addCompilationUnit(String packageName, String name, CompilationUnit compilationUnit); @Override void saveAll(); }### Answer: @Test public void testSaveAll() throws IOException { CompilationUnit compilationUnit = new CompilationUnit(); ClassOrInterfaceDeclaration classDeclaration = compilationUnit.addClass("TestClass"); classDeclaration.addPrivateField("FieldType", "fieldName").createGetter(); Path path = Files.createTempDirectory("cdt-test-dir"); sourceProject = new SourceProjectImpl(path); sourceProject.addCompilationUnit("com.github.kklisura", "TestClass", compilationUnit); sourceProject.saveAll(); File file = path.resolve("com/github/kklisura/TestClass.java").toFile(); assertNotNull(file); try { FileInputStream fileInputStream = new FileInputStream(file); int length; byte[] buffer = new byte[1024]; ByteArrayOutputStream result = new ByteArrayOutputStream(); while ((length = fileInputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } String outputFile = result.toString("UTF-8"); assertEquals( "public class TestClass {\n" + "\n" + " private FieldType fieldName;\n" + "\n" + " public FieldType getFieldName() {\n" + " return fieldName;\n" + " }\n" + "}\n", outputFile); } finally { file.delete(); } }
### Question: ChromeArguments { public static Builder defaults(boolean headless) { Builder builder = new Builder() .noFirstRun() .noDefaultBrowserCheck() .disableBackgroundNetworking() .disableBackgroundTimerThrottling() .disableClientSidePhishingDetection() .disableDefaultApps() .disableExtensions() .disableHangMonitor() .disablePopupBlocking() .disablePromptOnRepost() .disableSync() .disableTranslate() .metricsRecordingOnly() .safebrowsingDisableAutoUpdate(); if (headless) { builder.headless().disableGpu().hideScrollbars().muteAudio(); } return builder; } Boolean getHeadless(); Map<String, Object> getAdditionalArguments(); Boolean getNoDefaultBrowserCheck(); Boolean getNoFirstRun(); String getUserDataDir(); Integer getRemoteDebuggingPort(); Boolean getIncognito(); Boolean getDisableGpu(); Boolean getHideScrollbars(); Boolean getMuteAudio(); Boolean getDisableBackgroundNetworking(); Boolean getDisableBackgroundTimerThrottling(); Boolean getDisableClientSidePhishingDetection(); Boolean getDisableDefaultApps(); Boolean getDisableExtensions(); Boolean getDisableHangMonitor(); Boolean getDisablePopupBlocking(); Boolean getDisablePromptOnRepost(); Boolean getDisableSync(); Boolean getDisableTranslate(); Boolean getMetricsRecordingOnly(); Boolean getSafebrowsingDisableAutoUpdate(); static Builder builder(); static Builder defaults(boolean headless); static final String USER_DATA_DIR_ARGUMENT; }### Answer: @Test public void testDefaults() { ChromeArguments build = ChromeArguments.defaults(false).build(); assertDefaults(build); assertNull(build.getHeadless()); assertNull(build.getDisableGpu()); assertNull(build.getHideScrollbars()); assertNull(build.getMuteAudio()); }
### Question: ProcessLauncherImpl implements ProcessLauncher { @Override public Process launch(String program, List<String> args) throws IOException { List<String> arguments = new ArrayList<>(); arguments.add(program); arguments.addAll(args); ProcessBuilder processBuilder = new ProcessBuilder() .command(arguments) .redirectErrorStream(true) .redirectOutput(Redirect.PIPE); return processBuilder.start(); } @Override Process launch(String program, List<String> args); @Override boolean isExecutable(String binaryPath); }### Answer: @Test public void testLaunch() throws Exception { List<String> args = new ArrayList<>(); args.add("arg1"); args.add("arg2"); ProcessBuilder processBuilder = PowerMock.createMock(ProcessBuilder.class); PowerMock.expectNew(ProcessBuilder.class, new Class[] {}).andReturn(processBuilder); Capture<List<String>> captureCommands = Capture.newInstance(); expect(processBuilder.command(capture(captureCommands))).andReturn(processBuilder); expect(processBuilder.redirectErrorStream(true)).andReturn(processBuilder); expect(processBuilder.redirectOutput(Redirect.PIPE)).andReturn(processBuilder); Process process = mock(Process.class); expect(processBuilder.start()).andReturn(process); PowerMock.replayAll(ProcessBuilder.class, processBuilder); assertEquals(process, processLauncher.launch("program-name", args)); PowerMock.verify(ProcessBuilder.class, processBuilder); List<String> commands = captureCommands.getValue(); assertEquals(3, commands.size()); assertEquals("program-name", commands.get(0)); assertEquals("arg1", commands.get(1)); assertEquals("arg2", commands.get(2)); }
### Question: JavaClassBuilderImpl extends BaseBuilder implements JavaClassBuilder { @Override public void setJavaDoc(String comment) { if (StringUtils.isNotEmpty(comment)) { declaration.setJavadocComment( JavadocUtils.createJavadocComment(comment, INDENTATION_NO_INDENTATION)); } } JavaClassBuilderImpl(String packageName, String name, String annotationsPackage); @Override String getName(); @Override void setJavaDoc(String comment); @Override void addPrivateField(String name, String type, String description); @Override void addFieldAnnotation(String name, String annotationName); @Override void addAnnotation(String annotationName); @Override void generateGettersAndSetters(); @Override void addImport(String packageName, String object); static final Logger LOGGER; }### Answer: @Test public void testBasicClass() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture)); javaClassBuilder.setJavaDoc(""); replayAll(); javaClassBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "public class ClassName {\n" + "}\n" + "", compilationUnitCapture.getValue().toString()); verifyAll(); } @Test public void testSetJavadoc() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture)); javaClassBuilder.setJavaDoc("Java doc."); replayAll(); javaClassBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "\n" + "public class ClassName {\n" + "}\n", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: JavaClassBuilderImpl extends BaseBuilder implements JavaClassBuilder { @Override public void addAnnotation(String annotationName) { MarkerAnnotationExpr annotationExpr = new MarkerAnnotationExpr(); annotationExpr.setName(annotationName); declaration.addAnnotation(annotationExpr); importAnnotation(annotationName); } JavaClassBuilderImpl(String packageName, String name, String annotationsPackage); @Override String getName(); @Override void setJavaDoc(String comment); @Override void addPrivateField(String name, String type, String description); @Override void addFieldAnnotation(String name, String annotationName); @Override void addAnnotation(String annotationName); @Override void generateGettersAndSetters(); @Override void addImport(String packageName, String object); static final Logger LOGGER; }### Answer: @Test public void testBasicClassWithAnnotation() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture)); javaClassBuilder.addAnnotation("Annotation"); javaClassBuilder.addAnnotation("Deprecated"); replayAll(); javaClassBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "import com.github.kklisura.annotations.Annotation;\n" + "\n" + "@Annotation\n" + "@Deprecated\n" + "public class ClassName {\n" + "}\n" + "", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: JavaClassBuilderImpl extends BaseBuilder implements JavaClassBuilder { @Override public void generateGettersAndSetters() { List<FieldDeclaration> fields = declaration.getFields(); for (FieldDeclaration fieldDeclaration : fields) { String fieldName = fieldDeclaration.getVariables().get(0).getNameAsString(); setMethodJavadoc(fieldName, fieldDeclaration.createGetter()); setMethodJavadoc(fieldName, fieldDeclaration.createSetter()); } } JavaClassBuilderImpl(String packageName, String name, String annotationsPackage); @Override String getName(); @Override void setJavaDoc(String comment); @Override void addPrivateField(String name, String type, String description); @Override void addFieldAnnotation(String name, String annotationName); @Override void addAnnotation(String annotationName); @Override void generateGettersAndSetters(); @Override void addImport(String packageName, String object); static final Logger LOGGER; }### Answer: @Test public void testGenerateGettersAndSetters() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture)); replayAll(); javaClassBuilder.addPrivateField("privateField", "String", "Private field description"); javaClassBuilder.generateGettersAndSetters(); javaClassBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "public class ClassName {\n" + "\n" + " private String privateField;\n" + "\n" + " \n" + " public String getPrivateField() {\n" + " return privateField;\n" + " }\n" + "\n" + " \n" + " public void setPrivateField(String privateField) {\n" + " this.privateField = privateField;\n" + " }\n" + "}\n", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: JavaEnumBuilderImpl extends BaseBuilder implements JavaEnumBuilder { @Override public void setJavaDoc(String comment) { if (StringUtils.isNotEmpty(comment)) { declaration.setJavadocComment( JavadocUtils.createJavadocComment(comment, INDENTATION_NO_INDENTATION)); } } JavaEnumBuilderImpl(String packageName, String name); void addEnumConstant(String name, String value); @Override void setJavaDoc(String comment); @Override String getName(); }### Answer: @Test public void testBasicEnum() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit(eq(PACKAGE), eq(NAME), capture(compilationUnitCapture)); javaEnumBuilder.setJavaDoc(""); replayAll(); javaEnumBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "import com.fasterxml.jackson.annotation.JsonProperty;\n" + "\n" + "public enum EnumName {\n" + "}\n", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: JavaInterfaceBuilderImpl extends BaseBuilder implements JavaInterfaceBuilder { @Override public void addAnnotation(String annotationName) { Optional<AnnotationExpr> annotation = declaration.getAnnotationByName(annotationName); if (!annotation.isPresent()) { MarkerAnnotationExpr annotationExpr = new MarkerAnnotationExpr(); annotationExpr.setName(annotationName); declaration.addAnnotation(annotationExpr); importAnnotation(annotationName); } } JavaInterfaceBuilderImpl(String packageName, String name, String annotationsPackage); static void main(String[] args); @Override void setJavaDoc(String comment); @Override void addAnnotation(String annotationName); @Override void addMethodAnnotation(String methodName, String annotationName); @Override void addParametrizedMethodAnnotation( String methodName, String annotationName, String parameter); @Override String getName(); @Override void addImport(String packageName, String object); @Override void addMethod( String name, String description, List<MethodParam> methodParams, String returnType); }### Answer: @Test public void testBasicInterfaceWithAnnotation() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture)); interfaceBuilder.addAnnotation("Annotation"); interfaceBuilder.addAnnotation("Annotation"); interfaceBuilder.addAnnotation("Deprecated"); interfaceBuilder.addAnnotation("Deprecated"); replayAll(); interfaceBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n" + "\n" + "import com.github.kklisura.annotations.Annotation;\n" + "\n" + "@Annotation\n" + "@Deprecated\n" + "public interface InterfaceTest {\n" + "}\n" + "", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: JavaInterfaceBuilderImpl extends BaseBuilder implements JavaInterfaceBuilder { @Override public void addImport(String packageName, String object) { Name name = new Name(); name.setQualifier(new Name(packageName)); name.setIdentifier(object); if (!getPackageName().equalsIgnoreCase(packageName) && !CompilationUnitUtils.isImported(getCompilationUnit(), name)) { getCompilationUnit().addImport(new ImportDeclaration(name, false, false)); } } JavaInterfaceBuilderImpl(String packageName, String name, String annotationsPackage); static void main(String[] args); @Override void setJavaDoc(String comment); @Override void addAnnotation(String annotationName); @Override void addMethodAnnotation(String methodName, String annotationName); @Override void addParametrizedMethodAnnotation( String methodName, String annotationName, String parameter); @Override String getName(); @Override void addImport(String packageName, String object); @Override void addMethod( String name, String description, List<MethodParam> methodParams, String returnType); }### Answer: @Test public void testAddingImportsOnSamePackage() throws IOException { Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance(); sourceProject.addCompilationUnit( eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture)); replayAll(); interfaceBuilder.addImport(BASE_PACKAGE_NAME, "Test"); interfaceBuilder.addImport("java.util", "List"); interfaceBuilder.addImport("java.util", "List"); interfaceBuilder.addImport("java.util", "List"); interfaceBuilder.build(sourceProject); assertEquals( "package com.github.kklisura;\n\n" + "import java.util.List;\n" + "\n" + "public interface InterfaceTest {\n" + "}\n" + "", compilationUnitCapture.getValue().toString()); verifyAll(); }
### Question: CommandBuilder { static String buildReturnClasses(String returnType) { return "{" + buildReturnClassesRecursive(returnType) + "}"; } CommandBuilder( String basePackageName, JavaBuilderFactory javaBuilderFactory, String typesPackageName, String eventPackageName, String supportTypesPackageName); Builder build(Domain domain, DomainTypeResolver domainTypeResolver); }### Answer: @Test public void testBuildReturnClasses() { assertEquals("{Test.class}", buildReturnClasses("Test")); assertEquals("{List.class,Test.class}", buildReturnClasses("List<Test>")); assertEquals("{List.class,List.class,Test.class}", buildReturnClasses("List<List<Test>>")); }
### Question: StringUtils { public static String toEnumConstant(String value) { if (ENUM_CONSTANT_VALUE_OVERRIDES.get(value) != null) { return ENUM_CONSTANT_VALUE_OVERRIDES.get(value); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if ((Character.isUpperCase(c) && i > 0 && Character.isLowerCase(value.charAt(i - 1))) || (Character.isDigit(c) && i > 0 && Character.isLetter(value.charAt(i - 1))) || (Character.isUpperCase(c) && i > 1 && i < value.length() - 1 && Character.isUpperCase(value.charAt(i - 1))) && Character.isLowerCase(value.charAt(i + 1))) { sb.append("_"); } if (Character.isLetterOrDigit(c)) { sb.append(Character.toUpperCase(c)); } else { sb.append("_"); } } return sb.toString(); } static String toEnumConstant(String value); static String buildPackageName( String basePackageName, String packageName, String... subPackageNames); static String capitalize(String value); static String toEnumClass(String value); static String getReturnTypeFromGetter(String getterName); }### Answer: @Test public void testToEnumConstant() { assertEquals("ENUM_CONSTANT", StringUtils.toEnumConstant("enum_constant")); assertEquals("ENUM_CONSTANT", StringUtils.toEnumConstant("enumConstant")); assertEquals("ENUM_CONSTANT", StringUtils.toEnumConstant("Enum-Constant")); assertEquals("ENUM_CONSTANT_123", StringUtils.toEnumConstant("Enum-Constant123")); assertEquals("DOM_CONSTANT", StringUtils.toEnumConstant("DOMConstant")); assertEquals("DOM_CONSTANT", StringUtils.toEnumConstant("DOM*Constant")); assertEquals("NAN", StringUtils.toEnumConstant("NaN")); assertEquals("NEGATIVE_INFINITY", StringUtils.toEnumConstant("-Infinity")); assertEquals("NEGATIVE_0", StringUtils.toEnumConstant("-0")); }
### Question: StringUtils { public static String buildPackageName( String basePackageName, String packageName, String... subPackageNames) { StringBuilder stringBuilder = new StringBuilder(basePackageName + "." + packageName); if (subPackageNames != null) { for (String subPackageName : subPackageNames) { stringBuilder.append("."); stringBuilder.append(subPackageName); } } return stringBuilder.toString(); } static String toEnumConstant(String value); static String buildPackageName( String basePackageName, String packageName, String... subPackageNames); static String capitalize(String value); static String toEnumClass(String value); static String getReturnTypeFromGetter(String getterName); }### Answer: @Test public void testBuildPackageName() { assertEquals("com.github.kklisura", StringUtils.buildPackageName("com.github", "kklisura")); }
### Question: StringUtils { public static String capitalize(String value) { return org.apache.commons.lang3.StringUtils.capitalize(value); } static String toEnumConstant(String value); static String buildPackageName( String basePackageName, String packageName, String... subPackageNames); static String capitalize(String value); static String toEnumClass(String value); static String getReturnTypeFromGetter(String getterName); }### Answer: @Test public void testCapitalize() { assertEquals("TestCapitalization", StringUtils.capitalize("testCapitalization")); }
### Question: StringUtils { public static String getReturnTypeFromGetter(String getterName) { Matcher matcher = GETTER_NAME_PATTERN.matcher(getterName); if (matcher.matches()) { return toEnumClass(matcher.group(1)); } return toEnumClass(getterName); } static String toEnumConstant(String value); static String buildPackageName( String basePackageName, String packageName, String... subPackageNames); static String capitalize(String value); static String toEnumClass(String value); static String getReturnTypeFromGetter(String getterName); }### Answer: @Test public void testGetReturnTypeFromGetter() { assertEquals("Test", StringUtils.getReturnTypeFromGetter("test")); assertEquals("Test", StringUtils.getReturnTypeFromGetter("getTest")); assertEquals("Test", StringUtils.getReturnTypeFromGetter("gettest")); }