我写一个SpringBoot集成测试,我需要,而在同一时间使用一些真实的物体(如延伸JPARepository接口),与我的数据库的接口,以便能够与外部服务模拟的互动。
所以我们可以说我的测试等级如下表所示,
@Service
class MyService {
@Autowired
MyRepository myRepository; // This is the JPARepository which I want to use the real thing
@Autowired
OtherService otherService; // This one I really want to mock
public class myMethod() {
//Code which composes anEntity
//anEntity is not null
MyEntity myEntity = myRepository.save(anEntity); //after save myEntity is null
myEntity.getId(); // this will throw an NPE
}
}
现在,这里是我的测试类,
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
class MyServiceTest {
@InjectMocks
MyService service;
@Spy
@Autowired
MyRepository myRepository;
@Mock
OtherService otherService
public void testMyMethod() {
myService.myMethod();
}
}
基本上注入嘲笑和间谍的一切看上去都不错,但出于某种原因,当我打电话节省我的仓库,它返回一个空的对象,而不是实体。
有什么办法来解决这个问题?
相反,上述构建的,只是使用Spring引导本地注释@SpyBean
呦ualso需要自动装配测试类,这是在这种情况下MyService
。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
class MyServiceTest {
@SpyBean
MyRepository myRepository;
@Autowired
OtherService otherService
public void testMyMethod() {
myService.myMethod();
}
}