亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是什么導致了這個 mockito 異常?

是什么導致了這個 mockito 異常?

一只萌萌小番薯 2022-07-20 21:04:27
我正在為項目創建測試用例。項目是如何設計的,很難繼續進行簡單的單元測試,并且似乎缺少一個依賴項,以便使用 Mockito 來模擬函數和對象。這是我所擁有的:@RunWith(SpringRunner.class)public class RequestHandlerTest {    private byte[] buffer;    private Connection conn;    private Server server;    @Mock ResponseHandler response;    @Mock Services serviceImpl;    @InjectMocks RequestHandler request;    @Before    // This just creates the buffer in order to simulate sending and     // receiving a response across a server and client    public void createRequests();     @After    public void cleanUpBuffer(); // Cleans up buffer after test    @Test    public void TestReceiveMessage() {        doNothing().when(response.updataCache(conn, reqID));        ... // Do nothing for service function        handler.receiveMsg(conn, buffer);        // Verify request    }}我不確定是什么原因造成的,以及需要做些什么來解決這個問題。我嘗試設置初始化 Mockito,使用 @Autowired 將 @Mock 更改為 @MockBean,還嘗試使用包裝類設置我的值。有什么我可能會丟失的嗎?我以前從未見過這種情況。
查看完整描述

3 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

首先,你不需要在SpringRunner這里使用。替換@RunWith(SpringRunner.class)@RunWith(MockitoJUnitRunner.class)

其次,如果還是出現這個問題,嘗試使用next(假設RequestHandlerImpl是RequestHandler的實現):

@InjectMocks RequestHandler request = new RequestHandlerImpl();

甚至@InjectMocks RequestHandlerImpl request



查看完整回答
反對 回復 2022-07-20
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

這在 mockito2 2.xx 版本中得到解決。

org.powermock powermock-api-mockito2 2.0.9 測試


查看完整回答
反對 回復 2022-07-20
?
森林海

TA貢獻2011條經驗 獲得超2個贊

好的,所以在查看了這個之后,我看到有很多 bean 正在被 Autowired。所以我需要為我所依賴的類添加上下文配置。然后我可以使用 Mock 和 Inject Mock 的注釋。所以我的夾具變成了這樣:


@RunWith(SpringRunner.class)

@ContextConfiguration(classes = {RequestHandler.class, ResponseHandler.class,

      DataCache.class, Service.class})

public class RequestHandlerTest {

   @Mock private ResponseHandler response;

   @Mock private Service serv;


   @InjectMocks

   @Resource

   private RequestHandler request;


   public void setUp() {

      MockitoAnnotations.initMocks(this);


      // Add mock data logic using doAnswer or doNothing for void methods if needed 

      // and adding when().then() for mocking return values for other functions


   }


   @Test

   public void makeRequest() {

      assertTrue(request.sendRequest(Object message));

   }

}

從Mocking Void Methods with Mockito和這個問題的答案中提取信息。


查看完整回答
反對 回復 2022-07-20
  • 3 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號