3 回答

TA貢獻1796條經(jīng)驗 獲得超10個贊
如果測試數(shù)據(jù)庫連接,這里是舊的,但關于該主題的博客仍然不錯。您也應該能夠使用 TestContainers 來實現(xiàn)更簡單的數(shù)據(jù)庫創(chuàng)建。
如果您只需要在某些確切的操作(例如存儲庫保存)上測試一些失敗,您可以簡單地模擬存儲庫以進行測試運行:
var mockedBean = Mockito.mock(MyRepository.class);
var originalBean = ReflectionTestUtils.getField(articleService, fieldName);
Mockito.when(mockedBean.save(Mockito.any(MyEntity.class))).thenThrow(new RuntimeException("My test exception"));
ReflectionTestUtils.setField(myService, fieldName, mockedBean);
...
// test here
...
// set bean back for other test cases
ReflectionTestUtils.setField(myService, fieldName, originalBean);
添加回答
舉報