@Autowired annotation not working in junit for Service class












1














I am trying to test simple CRUD operation. Autowired annotation is working fine for Repository class but not working when I tried to use Service class.



@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---");
}
}









share|improve this question




















  • 1




    You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
    – watchme
    Apr 12 at 5:40






  • 1




    ... and the error you get (if you get an error)
    – watchme
    Apr 12 at 5:41










  • Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
    – Sanish Maharjan
    Apr 12 at 8:39












  • I think this link will help you: techbeacon.com/…
    – watchme
    Apr 12 at 8:53












  • It will be impossible to assist you without seeing your code and configuration.
    – Sam Brannen
    Apr 12 at 15:39
















1














I am trying to test simple CRUD operation. Autowired annotation is working fine for Repository class but not working when I tried to use Service class.



@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---");
}
}









share|improve this question




















  • 1




    You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
    – watchme
    Apr 12 at 5:40






  • 1




    ... and the error you get (if you get an error)
    – watchme
    Apr 12 at 5:41










  • Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
    – Sanish Maharjan
    Apr 12 at 8:39












  • I think this link will help you: techbeacon.com/…
    – watchme
    Apr 12 at 8:53












  • It will be impossible to assist you without seeing your code and configuration.
    – Sam Brannen
    Apr 12 at 15:39














1












1








1







I am trying to test simple CRUD operation. Autowired annotation is working fine for Repository class but not working when I tried to use Service class.



@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---");
}
}









share|improve this question















I am trying to test simple CRUD operation. Autowired annotation is working fine for Repository class but not working when I tried to use Service class.



@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---");
}
}






spring junit5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 13 at 3:54

























asked Apr 12 at 5:23









Sanish Maharjan

86




86








  • 1




    You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
    – watchme
    Apr 12 at 5:40






  • 1




    ... and the error you get (if you get an error)
    – watchme
    Apr 12 at 5:41










  • Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
    – Sanish Maharjan
    Apr 12 at 8:39












  • I think this link will help you: techbeacon.com/…
    – watchme
    Apr 12 at 8:53












  • It will be impossible to assist you without seeing your code and configuration.
    – Sam Brannen
    Apr 12 at 15:39














  • 1




    You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
    – watchme
    Apr 12 at 5:40






  • 1




    ... and the error you get (if you get an error)
    – watchme
    Apr 12 at 5:41










  • Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
    – Sanish Maharjan
    Apr 12 at 8:39












  • I think this link will help you: techbeacon.com/…
    – watchme
    Apr 12 at 8:53












  • It will be impossible to assist you without seeing your code and configuration.
    – Sam Brannen
    Apr 12 at 15:39








1




1




You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
– watchme
Apr 12 at 5:40




You are using spring right? Please post the class in which the autowired-annotation is not working and the service-class
– watchme
Apr 12 at 5:40




1




1




... and the error you get (if you get an error)
– watchme
Apr 12 at 5:41




... and the error you get (if you get an error)
– watchme
Apr 12 at 5:41












Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
– Sanish Maharjan
Apr 12 at 8:39






Yes, Im using spring. Autowired annotation is not working in Junit Test Class. Error: Unsatisfied Dependency Exception
– Sanish Maharjan
Apr 12 at 8:39














I think this link will help you: techbeacon.com/…
– watchme
Apr 12 at 8:53






I think this link will help you: techbeacon.com/…
– watchme
Apr 12 at 8:53














It will be impossible to assist you without seeing your code and configuration.
– Sam Brannen
Apr 12 at 15:39




It will be impossible to assist you without seeing your code and configuration.
– Sam Brannen
Apr 12 at 15:39












2 Answers
2






active

oldest

votes


















1














@Autowired annotation works fine when your test class has @RunWith(SpringRunner.class)
But if you use @RunWith(MockitoJUnitRunner.class), you should use @Mock instead @Autowired.
Could you share a code?






share|improve this answer

















  • 1




    Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
    – Sanish Maharjan
    Apr 12 at 8:48










  • Plz chk the code....This is the sample I want to do. @Nikita Sahan
    – Sanish Maharjan
    Apr 13 at 3:57





















0














Try add @ComponentScan("xx.xx") in your @Configuration class






share|improve this answer










New contributor




hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49788593%2fautowired-annotation-not-working-in-junit-for-service-class%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    @Autowired annotation works fine when your test class has @RunWith(SpringRunner.class)
    But if you use @RunWith(MockitoJUnitRunner.class), you should use @Mock instead @Autowired.
    Could you share a code?






    share|improve this answer

















    • 1




      Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
      – Sanish Maharjan
      Apr 12 at 8:48










    • Plz chk the code....This is the sample I want to do. @Nikita Sahan
      – Sanish Maharjan
      Apr 13 at 3:57


















    1














    @Autowired annotation works fine when your test class has @RunWith(SpringRunner.class)
    But if you use @RunWith(MockitoJUnitRunner.class), you should use @Mock instead @Autowired.
    Could you share a code?






    share|improve this answer

















    • 1




      Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
      – Sanish Maharjan
      Apr 12 at 8:48










    • Plz chk the code....This is the sample I want to do. @Nikita Sahan
      – Sanish Maharjan
      Apr 13 at 3:57
















    1












    1








    1






    @Autowired annotation works fine when your test class has @RunWith(SpringRunner.class)
    But if you use @RunWith(MockitoJUnitRunner.class), you should use @Mock instead @Autowired.
    Could you share a code?






    share|improve this answer












    @Autowired annotation works fine when your test class has @RunWith(SpringRunner.class)
    But if you use @RunWith(MockitoJUnitRunner.class), you should use @Mock instead @Autowired.
    Could you share a code?







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 12 at 6:59









    Nikita Sahan

    537




    537








    • 1




      Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
      – Sanish Maharjan
      Apr 12 at 8:48










    • Plz chk the code....This is the sample I want to do. @Nikita Sahan
      – Sanish Maharjan
      Apr 13 at 3:57
















    • 1




      Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
      – Sanish Maharjan
      Apr 12 at 8:48










    • Plz chk the code....This is the sample I want to do. @Nikita Sahan
      – Sanish Maharjan
      Apr 13 at 3:57










    1




    1




    Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
    – Sanish Maharjan
    Apr 12 at 8:48




    Im using Junit5 and I am using '@ExtendWith(SpringExtension.class)'. Test works fine in case of Repository class but '@Autowired' is not working when class with '@Service'. I am using Service class to access to db.
    – Sanish Maharjan
    Apr 12 at 8:48












    Plz chk the code....This is the sample I want to do. @Nikita Sahan
    – Sanish Maharjan
    Apr 13 at 3:57






    Plz chk the code....This is the sample I want to do. @Nikita Sahan
    – Sanish Maharjan
    Apr 13 at 3:57















    0














    Try add @ComponentScan("xx.xx") in your @Configuration class






    share|improve this answer










    New contributor




    hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0














      Try add @ComponentScan("xx.xx") in your @Configuration class






      share|improve this answer










      New contributor




      hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





















        0












        0








        0






        Try add @ComponentScan("xx.xx") in your @Configuration class






        share|improve this answer










        New contributor




        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        Try add @ComponentScan("xx.xx") in your @Configuration class







        share|improve this answer










        New contributor




        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer








        edited 3 hours ago









        Đinh Hồng Châu

        2,004134184




        2,004134184






        New contributor




        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 9 hours ago









        hw.chen

        1




        1




        New contributor




        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        hw.chen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49788593%2fautowired-annotation-not-working-in-junit-for-service-class%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'