【发布时间】:2018-06-28 00:03:40
【问题描述】:
我正在尝试为 Spring Boot 应用程序的业务层设置集成测试。单元测试工作正常,但集成测试不起作用。这是基本设置:
// entities
@Entity
Table(name="TOrder")
public class JPAOrder... {
}
@Entity
Table(name="TCustomer")
public class JPACustomer... {
}
// Repository interfaces
@Repository
public interface OrderRepository extends CrudRepository<JPAOrder, Long> {
...
}
@Repository
public interface CustomerRepository extends CrudRepository<JPACustomer, Long> {
...
}
// Business logic
@Service
@Transactional
public class OrderService ... {
...
@Autowired
private CustomerRepository customerRepository;
...
public Order createOrderForCustomer(final Order order, final Customer customer) {
...
}
}
// Test
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class OrderIntegrationTest {
@SpyBean
private OrderRepository orderRepository;
@Autowired
private OrderService orderService;
Order order = orderService.createOrderForCustomer(...);
}
启动应用程序给我这个错误
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...repository.OrderRepository#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [...repository.OrderRepository]: Specified class is an interface
...
如果我在集成测试中不使用@SpyBean 注解,OrderService 中的 orderRepository 就为空。 我一定错过了一些非常明显的东西,但我不知道是什么。 有什么建议吗?
【问题讨论】:
-
OrderService 也为空吗?
-
不,Autowired 在这里工作,只是不在依赖类中。
-
如果你不使用 Autowired 注释一个对象,spring 不能做任何事情。对于您的情况,您只想测试业务逻辑部分,您可以模拟业务类所需的依赖项(在本例中是存储库)。您可以简单地使用 MockBean 而不是 SpyBean 来注释您的 orderRepository。在您的测试方法中,您应该使用 mockito 的 when-then 方法模拟此存储库使用的方法的行为
-
@barbakini:正如标题所说,我想做一个集成测试。模拟存储库工作得很好,但我想确保服务真的做他们应该做的。不是独立的,而是当它们与服务集成时。
标签: java spring-boot integration-testing