我正在尝试为服务编写测试。但我没有成功地嘲笑repository
依赖性。其他非存储库依赖项已成功模拟。存储库实例始终是实际实现,而不是模拟实例。
我正在使用 Spring Boot 和 Spring Data JPA 来构建应用程序。 Mockito 用于模拟。我设法将问题提炼到一个测试项目中。完整的测试项目已上线GitHub https://github.com/ChrisZhong/spring-boot-data-jpa-mockito-testing。以下是测试项目的代码片段;以下是PersonServiceTest
class.
更新1: before()
应该检查代码personRepository
not personService
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(App.class)
@WebAppConfiguration
@TestExecutionListeners({ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, SqlScriptsTestExecutionListener.class})
@Transactional
@ActiveProfiles({"mock-some-bean", "mock-person-repository"})
public class PersonServiceTest {
@Inject
private SomeBean someBean;
@Inject
private PersonRepository personRepository;
@Inject
private PersonService personService;
@Before
public void before() {
assertThat(mockingDetails(someBean).isMock(), is(true));
assertThat(mockingDetails(personRepository).isMock(), is(true));
}
@Test
public void doSomething() throws Exception { ... }
}
测试类使用两个配置文件:mock-some-bean
and mock-person-repository
。基本上,我使用配置文件来确定应该嘲笑什么。在进行任何测试之前,我断言someBean
and personService
是模拟实例。someBean
被正确地嘲笑但是personService
总是失败。下面的代码是来自TestConfig
class.
@Configuration
public class TestConfig {
private static final Logger logger = LoggerFactory.getLogger(TestConfig.class);
@Bean
@Profile("mock-some-bean")
public SomeBean someBean() {
logger.info("Mocking: {}", SomeBean.class);
return mock(SomeBean.class);
}
@Bean
@Profile("mock-person-repository")
public PersonRepository personRepository() {
logger.info("Mocking: {}", PersonRepository.class);
return mock(PersonRepository.class);
}
}
更新2:问题更清楚了
我缺少什么?看来 Spring Data JPA 总是创建一个实例并忽略@Bean
定义在TestConfig
班级。如何“告诉”Spring Data JPA 不要创建实例?我很感谢我能得到的任何帮助来解决这个问题。
更新3:仍在寻找理想的解决方案
我仍然希望有一个解决方案。尽管我已将解决方案标记为已接受,但建议的解决方案并不理想。因为存在不同级别的集成测试(从端到端测试到具有一小组依赖项的非常窄范围的测试)。