使用 Guice 将字符串注入 class 进行 JUnit 测试

Inject string into class using Guice for JUnit test

我遇到一种情况,我需要测试一个函数,但 class 注入了这样的字符串值:

public class SomeClass{
    @Inject
    @Named("api")
    private String api;

    public Observable<String> get(String uuidData){
        //do something with "api" variable
    }
}

现在如何从我的 JUnit 测试用例中注入它?我也在使用 Mockito,但它不允许我模拟原始类型。

这里好像有两个选项:

选项 1:在 JUnit 测试的 @Before 中设置注入

//test doubles
String testDoubleApi;

//system under test
SomeClass someClass;

@Before
public void setUp() throws Exception {
    String testDoubleApi = "testDouble";
    Injector injector = Guice.createInjector(new Module() {
        @Override
        protected void configure(Binder binder) {
            binder.bind(String.class).annotatedWith(Names.named("api")).toInstance(testDouble);
        }
    });
    injector.inject(someClass);
}

选项 2: 重构您的 class 以使用构造函数注入

public class SomeClass{
    private String api;

    @Inject
    SomeClass(@Named("api") String api) {
        this.api = api;
    }

    public Observable<String> get(String uuidData){
        //do something with "api" variable
    }
}

现在您的 @Before 方法将如下所示:

//test doubles
String testDoubleApi;

//system under test
SomeClass someClass;

@Before
public void setUp() throws Exception {
    String testDoubleApi = "testDouble";
    someClass = new SomeClass(testDoubleApi);
}

在这两个选项中,我认为第二个更可取。您可以看到它导致更少的样板文件,并且 class 即使没有 Guice 也可以测试。