我正在尝试编写单元测试用例以使用一些 mockito 作为模拟框架来测试我的代码,在这之间我遇到了一个问题,我无法模拟我在测试类中使用 Google Guice 进行的注入。
我尝试直接注入对象,它可以工作,但谷歌注入没有运气。
class SomeClassToCreateWiskey{
// Some Service
@Inject
@Named("dataCreation")
DataCreation dataCreation;
public apis(){
Injector injector = Guice.createInjector(new DataCreationModel());
injector.injectMembers(this);
int port = config().getInteger("http.port", 8080);
Router router = Router.router(vertx);
router.route("/api/getAll").handler(this::getAll);
}
// getAll method will return some json result
}
测试上述 API 的测试类
class SomeClassToCreateWiskeyTest{
@Mock
private DataCreation dataCreation;
// setting up before and after config
@Before
MockitoAnnotations.initMocks(this);
......
@After
......
@Test
public void testGetAll(){
Map<Integer, Whisky> dataSets = new LinkedHashMap<>();
Whisky w1 = new Whisky("Bowmore 15 Years Laimrig", "Scotland, Islay");
Whisky w2 = new Whisky("Talisker 57° kya h", "Scotland, Island");
Async async = context.async();
dataSets.put(w1.getId(), w1);
dataSets.put(w2.getId(), w2);
when(dataCreationDao.getData()).thenReturn(dataSets);
when(dataCreation.getData()).thenReturn(dataSets);
HttpClient client = vertx.createHttpClient();
client.getNow(port, "localhost", "/api/getAll", response -> {
response.bodyHandler(body -> {
System.out.println(body.toString());
client.close();
async.complete();
});
});
}
}
牧羊人nacy
相关分类