aboutsummaryrefslogtreecommitdiff
path: root/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccount.java
blob: 37bd4a4c2d23d20eb24e192b1de0dd1cb14700d6 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.xtremelabs.robolectric.shadows;

import android.accounts.Account;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import android.text.TextUtils;

import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;
import com.xtremelabs.robolectric.internal.RealObject;

import java.lang.reflect.Field;

@Implements(Account.class)
public class ShadowAccount {
    @RealObject
    private Account realObject;

    public void __constructor__(String name, String type) throws Exception {
        set(name, type);
    }

    public void __constructor__(Parcel parcel) throws Exception {
        set(parcel.readString(), parcel.readString());
    }

    @Override
    @Implementation
    public String toString() {
        return "Account {name=" + realObject.name + ", type=" + realObject.type + "}";
    }

    @Implementation
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(realObject.name);
        dest.writeString(realObject.type);
    }

    public static final Creator<Account> CREATOR =
        new Creator<Account>() {
            @Override
            public Account createFromParcel(Parcel source) {
                return new Account(source);
            }

            @Override
            public Account[] newArray(int size) {
                return new Account[size];
            }
        };

    private void set(String name, String type) throws Exception {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(type)) throw new IllegalArgumentException();

        Field nameF = realObject.getClass().getField("name");
        nameF.setAccessible(true);
        nameF.set(realObject, name);

        Field typeF = realObject.getClass().getField("type");
        typeF.setAccessible(true);
        typeF.set(realObject, type);
    }

    @Override
    @Implementation
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof Account)) return false;
        final Account other = (Account)o;
        return realObject.name.equals(other.name) && realObject.type.equals(other.type);
    }

    @Override
    @Implementation
    public int hashCode() {
        int result = 17;
        result = 31 * result + realObject.name.hashCode();
        result = 31 * result + realObject.type.hashCode();
        return result;
    }

    public static void reset() {
        Robolectric.Reflection.setFinalStaticField(Account.class, "CREATOR", CREATOR);
    }
}