• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package example.hilt;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 
21 import android.content.Context;
22 import android.os.Build;
23 import androidx.test.core.app.ApplicationProvider;
24 import androidx.test.ext.junit.runners.AndroidJUnit4;
25 import dagger.hilt.android.testing.BindValue;
26 import dagger.hilt.android.testing.HiltAndroidRule;
27 import dagger.hilt.android.testing.HiltAndroidTest;
28 import dagger.hilt.android.testing.HiltTestApplication;
29 import example.common.CoffeeLogger;
30 import example.common.CoffeeMaker;
31 import example.common.Heater;
32 import javax.inject.Inject;
33 import org.junit.Rule;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.robolectric.annotation.Config;
37 
38 /** Tests using a fake heater. */
39 @HiltAndroidTest
40 @Config(sdk = {Build.VERSION_CODES.P}, application = HiltTestApplication.class)
41 @RunWith(AndroidJUnit4.class)
42 public final class CoffeeAppFakeHeaterTest {
43   public @Rule HiltAndroidRule rule = new HiltAndroidRule(this);
44 
45   final class FakeHeater implements Heater {
46     private boolean heating;
47 
48     @Override
on()49     public void on() {
50       this.heating = true;
51       logger.log("~ ~ ~ fake heating ~ ~ ~");
52     }
53 
54     @Override
off()55     public void off() {
56       this.heating = false;
57     }
58 
59     @Override
isHot()60     public boolean isHot() {
61       return heating;
62     }
63   }
64 
65   @Inject CoffeeMaker maker;
66   @Inject CoffeeLogger logger;
67 
68   @BindValue Heater fakeHeater = new FakeHeater();
69 
70   @Test
testApplicationClass()71   public void testApplicationClass() throws Exception {
72     assertThat((Context) ApplicationProvider.getApplicationContext())
73         .isInstanceOf(HiltTestApplication.class);
74   }
75 
76   @Test
testLogs()77   public void testLogs() throws Exception {
78     rule.inject();
79     assertThat(logger.logs()).isEmpty();
80     maker.brew();
81     assertThat(logger.logs())
82         .containsExactly(
83             "~ ~ ~ fake heating ~ ~ ~",
84             "=> => pumping => =>",
85             " [_]P coffee! [_]P ")
86         .inOrder();
87   }
88 }
89