我正在嘗試編寫單元測試用例以使用一些 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(); }); }); } }
1 回答

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
基本上,您有一個在您執(zhí)行請求時創(chuàng)建的注入器,并且使用該注入器是因為您使用requestInjection(this)
. 這將覆蓋您使用的任何類型的注入。
具體來說,這就是正在發(fā)生的事情:
Mockito 注入模擬。
你用
injector.injectMembers(this)
.
所以不要在start
方法中創(chuàng)建注入器:在適當?shù)牡胤揭苿铀?,這取決于你使用的各種框架。
添加回答
舉報
0/150
提交
取消