繁体   English   中英

使用Guice for JUnit测试将字符串注入类中

[英]Inject string into class using Guice for JUnit test

我有一种情况需要测试一个函数,但是类已经注入了String值,如下所示:

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:重构您的类以使用构造函数注入

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);
}

在这两个选项中,我会说第二个更好。 您可以看到它导致更少的锅炉板,即使没有Guice,也可以测试该类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM