gpt4 book ai didi

java - 使用 Guice 将字符串注入(inject)类进行 JUnit 测试

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:23 25 4
gpt4 key购买 nike

我遇到这样一种情况,我需要测试一个函数,但是类已经注入(inject)了这样的字符串值:

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

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

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

最佳答案

看起来这里有两个选项:

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

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

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 也可以测试该类。

关于java - 使用 Guice 将字符串注入(inject)类进行 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40915711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com