我存根我的存储库时遇到问题。建议我仅创建另一个application.properties(我尚未完成),并使用内存数据库(例如H2)。我想知道是否可以仅对调用进行存根处理,以便在调用myDataService.findById(id)而不是尝试从数据库中获取该对象时,是否可以返回模拟对象?一般来说,我是为单元测试和Spring Boot编写模拟游戏的新手,所以也许我错过了一些东西。下面的代码(为简化起见,使名称通用,可在此处发布)。我的考试课public class MyServiceImplTest { private MyDataService myDataService; private NyService myService; private MyRepository myRepository; @Before public void setUp() { myDataService = Mockito.mock(MyDataServiceImpl.class); myService = new MyServiceImpl(myDataService); } @Test public void getById_ValidId() { doReturn(MyMockData.getMyObject()).when(myDataService).findById("1"); when(myService.getById("1")).thenReturn(MyMockData.getMyObject()); MyObject myObject = myService.getById("1"); //Whatever asserts need to be done on the object myObject }}用于对数据层进行服务调用的类@Servicepublic class MyServiceImpl implements MyService { MyDataService myDataService; @Autowired public MyServiceImpl(MyDataService myDataService) { this.myDataService = myDataService; } @Override public MyObject getById(String id) { if(id == null || id == "") { throw new InvalidRequestException("Invalid Identifier"); } MyObject myObj; try { myObj = myDataService.findById(id); }catch(Exception ex) { throw new SystemException("Internal Server Error"); } return myObj; }}这是我测试中遇到的问题。调用findById()方法时,变量存储库为null,因此在尝试执行repository.findOne(id)时会抛出异常。这是我试图模拟的内容,但是存储库给了我一些问题。@Repository@Qualifier("MyRepo")public class MyDataServiceImpl { @PersistenceContext private EntityManager em; private MyRepository repository; @Autowired public MyDataServiceImpl(MyRepository repository) { super(repository); this.repository = repository; }
添加回答
举报
0/150
提交
取消