spring boot integration test (business layer)

2019-03-04 17:50发布

问题:

I'm trying to setup integration tests for the business layer of a spring boot application. The Unit-Tests work fine but integration tests don't work. Here's the basic setup:

// 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(...);
}

Starting the application gives me this error

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
...

If I don't use the @SpyBean annotation in the integration test the orderRepository in the OrderService is simply null. I must be missing something really obvious but I can't figure out what. Any suggestions?

回答1:

For me also this exception occured. Please see This Question.

Try changing @TestPropertySource(..) to

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
            value={"spring.profiles.active=integrationtest"})

Hope it helps !