-
Junit 的使用
1. 为了方便程序员测试某一个方法而使用
2. 在方法上面加上 @Test 并引用 5.X 版本
3. 就能在方法前面看到可运行的按钮
public class Homework07 {
public static void main(String[] args) {
}
@Test
public void testList() {
DAO<User> dao = new DAO<>();
dao.save("第一个", new User(123, 23, "小米"));
dao.save("第二个", new User(234, 32, "小华"));
dao.save("第三个", new User(345, 66, "小钟"));
dao.save("第四个", new User(456, 45, "小三"));
List<User> list1 = dao.list();
System.out.println(list1);
dao.update("第二个",new User(555, 78, "小小"));
List<User> list2 = dao.list();
System.out.println(list2);
dao.delete("第一个");
List<User> list3 = dao.list();
System.out.println(list3);
}
}
class DAO<T> {
private Map<String, T> map = new HashMap<>();
public void save(String id, T entity) {
getMap().put(id, entity);
}
public T get(String id) {
return getMap().get(id);
}
public void update(String id, T entity) {
getMap().put(id, entity);
}
public List<T> list() {
ArrayList<T> list = new ArrayList<>();
Set<String> strings = getMap().keySet();
for (String key : strings) {
list.add(getMap().get(key));
}
return list;
// return new ArrayList<>(getMap().values());
}
public void delete(String id) {
getMap().remove(id);
}
public Map<String, T> getMap() {
return map;
}
public void setMap(Map<String, T> map) {
this.map = map;
}
}
class User {
private int id;
private int age;
private String name;
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id && age == user.age && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, age, name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
运行结果:
[User{id=234, age=32, name='小华'}, User{id=456, age=45, name='小三'}, User{id=345, age=66, name='小钟'}, User{id=123, age=23, name='小米'}]
[User{id=555, age=78, name='小小'}, User{id=456, age=45, name='小三'}, User{id=345, age=66, name='小钟'}, User{id=123, age=23, name='小米'}]
[User{id=555, age=78, name='小小'}, User{id=456, age=45, name='小三'}, User{id=345, age=66, name='小钟'}]