Mockito Spring Boot Java中服务类内部的Mocking Local方法


@Service
public class MyServiceImpl implements MyService {
@Autowired
SomeOtherService otherService;    
@Override
public List<Something> getSomething(Integer id) {
Something s = otherService.getOfSomething(id)
return doSomething(s.getId());
}
@Override
public List<Something> doSomething(Integer id) {
List<Something> list = new ArrayList<>();
// --- Some Logic ---
return list;
}
}

我有一个Service Class,它的结构和上面一样简单。我一直在弄清楚如何模拟在我单元测试其方法的相同服务类中存在的方法(即如何在单元测试getSomething时模拟doSomething()方法)。有人能帮我嘲笑本地方法的服务方法我是单元测试吗?谢谢你

我的测试现在如下所示

@Mock
SomeOtherService otherService;
@InjectMock
MyServiceImpl myServiceImpl;
@Test
public void testGetSomething() {
Something s = new Something();
when(otherService.getOfSomething(anyInt())).thenReturn(s);
List<Something> list = myServiceImpl.getSomething(10);
verify(otherService, times(1)).getOfSomething(anyInt());
}

如果你真的需要,你可以使用Spy。基本上,您将包装原始服务对象并只模拟doSomething方法。

然而,我认为更好的方法是为可测试性设计:只需将doSomething方法提取到单独的类中。

最新更新