forked from matyb/java-koans
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAboutObjects.java
More file actions
executable file
·63 lines (51 loc) · 1.52 KB
/
AboutObjects.java
File metadata and controls
executable file
·63 lines (51 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package beginner;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import com.sandwich.koan.Koan;
public class AboutObjects {
@Koan
public void newObjectInstancesCanBeCreatedDirectly() {
assertEquals(new Object() instanceof Object, __);
}
@Koan
public void allClassesInheritFromObject() {
class Foo {}
Class<?>[] ancestors = getAncestors(new Foo());
assertEquals(ancestors[0], __);
assertEquals(ancestors[1], __);
}
@Koan
public void objectToString() {
Object object = new Object();
// TODO: Why is it best practice to ALWAYS override toString?
String expectedToString = MessageFormat.format("{0}@{1}", Object.class.getName(), Integer.toHexString(object.hashCode()));
assertEquals(expectedToString, __); // hint: object.toString()
}
@Koan
public void toStringConcatenates() {
final String string = "ha";
Object object = new Object() {
@Override public String toString() {
return string;
}
};
assertEquals(string + object, __);
}
@Koan
public void toStringIsTestedForNullWhenInvokedImplicitly() {
String string = "string";
assertEquals(string + null, __);
}
private Class<?>[] getAncestors(Object object) {
List<Class<?>> ancestors = new ArrayList<Class<?>>();
Class<?> clazz = object.getClass();
while(clazz != null) {
ancestors.add(clazz);
clazz = clazz.getSuperclass();
}
return ancestors.toArray(new Class[]{});
}
}