@Autowired注释在Junit for Service类中不起作用

时间:2018-04-12 05:23:42

标签: spring junit5

我正在尝试测试简单的CRUD操作。 Autowired annotation适用于Repository类,但在我尝试使用Service类时无效。

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringDataJpaConfig.class })
class AddCustomerTest {

    @Autowired
    //This works fine but when I try using CustomerService it shows error 

    private CustomerRepository customerRepository;

    private static final Customer testCustomer = new Customer();
    private static final Product testProduct = new Product();
    private static final ProductCategory testProductCategory = new ProductCategory();

    @BeforeAll
    static void setUp() {
        testProduct.setProductId(169);
        testProductCategory.setProductCategoryId(167);
        testCustomer.setCustomerAddress("Kamaladi");
        testCustomer.setCustomerEmail("test@gmail.com");
        testCustomer.setCustomerName("TestMan");
        testCustomer.setCustomerPhoneNo("9834223344");
        testCustomer.setFileUploadLocation("Sample");
        testCustomer.setProduct(testProduct);
        testCustomer.setProductCategory(testProductCategory);
    }

    @DisplayName("Add Customer Test")
    @Test
    void addCustomerDataTest() {
        customerRepository.save(testCustomer);
        Customer expected = customerRepository.findOne(testCustomer.getCustomerId());
        System.out.println("Customer Id:" + testCustomer.getCustomerId());
        assertEquals(expected.getCustomerId(), testCustomer.getCustomerId(), "---Add CustomerData Test 1 Failed---");
        assertEquals(expected.getCustomerAddress(),testCustomer.getCustomerAddress(),"---Add CustomerData Test 2 Failed---");
    }
}

1 个答案:

答案 0 :(得分:0)

尝试在您的@ComponentScan("xx.xx")类中添加@Configuration