Skip to content

Commit 4e053c7

Browse files
committed
Merge pull request #80 from if12b062/master
Added setParser() to HawkBuilder
2 parents 351e466 + 07d8646 commit 4e053c7

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

hawk/src/main/java/com/orhanobut/hawk/HawkBuilder.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,11 @@ public HawkBuilder setCallback(Callback callback) {
8181
return this;
8282
}
8383

84+
public HawkBuilder setParser(Parser parser) {
85+
this.parser = parser;
86+
return this;
87+
}
88+
8489
public Context getContext() {
8590
return context;
8691
}

hawk/src/test/java/com/orhanobut/hawk/HawkBuilderTest.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
import android.app.Activity;
44
import android.content.Context;
5+
import android.text.TextUtils;
6+
7+
import com.google.gson.Gson;
8+
import com.google.gson.GsonBuilder;
9+
import com.google.gson.JsonSyntaxException;
10+
import com.orhanobut.hawk.GsonParser;
511

612
import junit.framework.TestCase;
713

@@ -13,6 +19,10 @@
1319
import org.robolectric.RobolectricGradleTestRunner;
1420
import org.robolectric.annotation.Config;
1521

22+
import java.lang.reflect.Type;
23+
24+
import dalvik.annotation.TestTarget;
25+
1626
import static org.assertj.core.api.Assertions.assertThat;
1727

1828
/**
@@ -30,6 +40,28 @@ public HawkBuilderTest() {
3040
builder = Hawk.init(context);
3141
}
3242

43+
class CustomParser implements Parser {
44+
private final Gson gson;
45+
46+
public CustomParser(Gson gson) {
47+
this.gson = gson;
48+
}
49+
50+
@Override
51+
public <T> T fromJson(String content, Type type) throws JsonSyntaxException {
52+
if (TextUtils.isEmpty(content)) {
53+
return null;
54+
}
55+
return gson.fromJson(content, type);
56+
}
57+
58+
@Override
59+
public String toJson(Object body) {
60+
return gson.toJson(body);
61+
}
62+
63+
}
64+
3365
@Before
3466
public void setup() {
3567
builder = new HawkBuilder(context);
@@ -149,6 +181,14 @@ public void testDefaultParser() {
149181
assertThat(builder.getParser()).isInstanceOf(GsonParser.class);
150182
}
151183

184+
@Test
185+
public void testCustomParser() {
186+
CustomParser parser = new CustomParser(new Gson());
187+
builder.setParser(parser)
188+
.build();
189+
assertThat(builder.getParser()).isInstanceOf(CustomParser.class);
190+
}
191+
152192
@Test
153193
public void testDefaultEncoded() {
154194
builder.build();

0 commit comments

Comments
 (0)