Getting NullPointerException while calling nested method of Service class using mockito












1














I am writing JUnit test cases for my Service classes.
I have created dummy data to understand my scenario.



@Service
MainClass {
@Autowired
C c;
public void someServiceMethod(){
ResultClass someResult = c.getResult(string,string, int, int, List<String>,boolean);
}
}

@Service
public class C {
@Autowired
SomeRepository someRepository;
public ResultClass getResult(string,string, int, int, List<String>,boolean){
ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);
}
}

@Test
MainClassTest {
@MockBean
SomeRepository someRepository;
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);

//calling MainClass method
MainClass.someServiceMethod();
}


Class C's getSomeData() method returning ABC class object which is NULL and latter setting into another same class type object.
After setting value I am getting NULLPointerException as ABC is NULL.
Anybody have any idea where I am going wrong?










share|improve this question






















  • I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:26










  • What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
    – Ken Chan
    Dec 27 '18 at 16:29










  • @KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:37
















1














I am writing JUnit test cases for my Service classes.
I have created dummy data to understand my scenario.



@Service
MainClass {
@Autowired
C c;
public void someServiceMethod(){
ResultClass someResult = c.getResult(string,string, int, int, List<String>,boolean);
}
}

@Service
public class C {
@Autowired
SomeRepository someRepository;
public ResultClass getResult(string,string, int, int, List<String>,boolean){
ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);
}
}

@Test
MainClassTest {
@MockBean
SomeRepository someRepository;
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);

//calling MainClass method
MainClass.someServiceMethod();
}


Class C's getSomeData() method returning ABC class object which is NULL and latter setting into another same class type object.
After setting value I am getting NULLPointerException as ABC is NULL.
Anybody have any idea where I am going wrong?










share|improve this question






















  • I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:26










  • What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
    – Ken Chan
    Dec 27 '18 at 16:29










  • @KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:37














1












1








1







I am writing JUnit test cases for my Service classes.
I have created dummy data to understand my scenario.



@Service
MainClass {
@Autowired
C c;
public void someServiceMethod(){
ResultClass someResult = c.getResult(string,string, int, int, List<String>,boolean);
}
}

@Service
public class C {
@Autowired
SomeRepository someRepository;
public ResultClass getResult(string,string, int, int, List<String>,boolean){
ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);
}
}

@Test
MainClassTest {
@MockBean
SomeRepository someRepository;
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);

//calling MainClass method
MainClass.someServiceMethod();
}


Class C's getSomeData() method returning ABC class object which is NULL and latter setting into another same class type object.
After setting value I am getting NULLPointerException as ABC is NULL.
Anybody have any idea where I am going wrong?










share|improve this question













I am writing JUnit test cases for my Service classes.
I have created dummy data to understand my scenario.



@Service
MainClass {
@Autowired
C c;
public void someServiceMethod(){
ResultClass someResult = c.getResult(string,string, int, int, List<String>,boolean);
}
}

@Service
public class C {
@Autowired
SomeRepository someRepository;
public ResultClass getResult(string,string, int, int, List<String>,boolean){
ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);
}
}

@Test
MainClassTest {
@MockBean
SomeRepository someRepository;
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);

//calling MainClass method
MainClass.someServiceMethod();
}


Class C's getSomeData() method returning ABC class object which is NULL and latter setting into another same class type object.
After setting value I am getting NULLPointerException as ABC is NULL.
Anybody have any idea where I am going wrong?







java spring-boot junit mockito






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 27 '18 at 16:21









Nizamuddin

184




184












  • I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:26










  • What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
    – Ken Chan
    Dec 27 '18 at 16:29










  • @KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:37


















  • I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:26










  • What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
    – Ken Chan
    Dec 27 '18 at 16:29










  • @KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
    – Stalemate Of Tuning
    Dec 27 '18 at 16:37
















I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
– Stalemate Of Tuning
Dec 27 '18 at 16:26




I admit I am not really familiar with this syntax for using Mockito, but it looks to me like your getSomeData method returns a ResultClass, but when you stub it you are returning a SomeRepository object. Try creating a ResultClass and return that instead.
– Stalemate Of Tuning
Dec 27 '18 at 16:26












What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
– Ken Chan
Dec 27 '18 at 16:29




What is your intention ? Do you want to only mock the result of someRepository 's getSomeData() and test MainClass 's someServiceMethod() ?
– Ken Chan
Dec 27 '18 at 16:29












@KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
– Stalemate Of Tuning
Dec 27 '18 at 16:37




@KenChan Oh yeah that's a good point. If OP was intending to test someServiceMethod then OP should be stubbing getResult not getSomeData. A little more info is needed I think.
– Stalemate Of Tuning
Dec 27 '18 at 16:37












3 Answers
3






active

oldest

votes


















1














You are not returning expected object while writing mock statement



    @Service
public class C {
@Autowired
SomeRepository someRepository;
public ResultClass getResult(string,string, int, int, List<String>,boolean){
ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);

//Your return type should be ResultClass
// Where your return statement
// What is ABC?
}
}

@Test
MainClassTest {
@MockBean
SomeRepository someRepository;
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);
// Why are you returning SomeRepository, This Should return object of ABC

@MockBean
ABC mockResultClass
when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(mockResultClass);

//calling MainClass method
MainClass.someServiceMethod();
}





share|improve this answer





























    1














    You are calling MainClass.someServiceMethod() which in turn calls getResult of class C. You should be mocking class C and using when-thenReturn on getResult() of C class if your intention is to test someServiceMethod() of Main class. Autowired will not work here since this is a Unit test and hence the instance of C c in Main class will be null.
    Something like below:



    @MockBean
    C c;
    when(c.getResult(anyString(), anyString(),anyInt(),anyInt(), any(List.class), anyBoolean()).thenReturn(someResult);

    c.getResult(string,string, int, int, List<String>,boolean);





    share|improve this answer































      0














      So, first of all, we need to be clear on what exactly you are unit testing. If you are trying to unit test someServiceMethod inside of MainClass, then that means you should NOT be also testing the functionality of someRepository. The idea is that each unit test should only be testing just that, a unit of code. So, to do that we need to use stubs as stand-ins for what would actually happen when you call methods owned by other classes. Then, we would write a differrent unit test just for someRepository.getSomeData() to confirm that it is also working as intended. In this manner, when get an error later down the line we will know exactly where we are encountering an issue.



      Another issue I see is there is an apparent mismatch of return types for getResult() in C. The method says it returns a ResultClass, but when you call getSomeData you are expecting an ABC object. Either you left out the details where you convert the object back to a ResultClass, or that is a mistake. I'm going to assume the former unless you say otherwise.



      With that in mind, let's write our test. Here's how I would write the test:



      @RunWith(SpringRunner.class)
      public class MainClassTest {

      @Mock
      C c;

      @InjectMocks
      MainClass mainClass;

      @Test
      public void testSomeServiceMethod {

      ResultClass resultClass = new ResultClass(); //relevant constructor details here, mockbean, etc. you get the idea

      //set any desired data for resultClass here

      Mockito.when(c.getResult(anyString(), anyString(),
      anyInt(), anyInt(), any(List.class), anyBoolean()))
      .thenReturn(resultClass);

      ResultClass newResult = mainClass.someServiceMethod();

      //relevant test assertions here
      }
      }


      As you can see, we are creating a ResultClass in the test, and telling Mockito to return that when getResult is called instead of what you would normally expect it to return. While the functionality may seem limited now, this is preferred as we only testing the MainClass and not the rest of our method calls.



      In addition to this, we can (and should) write tests for getResult in C, and getSomeData in SomeRepository. I will leave it to you to write those tests.



      EDIT: accidentally posted a bit early, fixing now.






      share|improve this answer























        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%2f53947954%2fgetting-nullpointerexception-while-calling-nested-method-of-service-class-using%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        You are not returning expected object while writing mock statement



            @Service
        public class C {
        @Autowired
        SomeRepository someRepository;
        public ResultClass getResult(string,string, int, int, List<String>,boolean){
        ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);

        //Your return type should be ResultClass
        // Where your return statement
        // What is ABC?
        }
        }

        @Test
        MainClassTest {
        @MockBean
        SomeRepository someRepository;
        when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);
        // Why are you returning SomeRepository, This Should return object of ABC

        @MockBean
        ABC mockResultClass
        when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(mockResultClass);

        //calling MainClass method
        MainClass.someServiceMethod();
        }





        share|improve this answer


























          1














          You are not returning expected object while writing mock statement



              @Service
          public class C {
          @Autowired
          SomeRepository someRepository;
          public ResultClass getResult(string,string, int, int, List<String>,boolean){
          ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);

          //Your return type should be ResultClass
          // Where your return statement
          // What is ABC?
          }
          }

          @Test
          MainClassTest {
          @MockBean
          SomeRepository someRepository;
          when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);
          // Why are you returning SomeRepository, This Should return object of ABC

          @MockBean
          ABC mockResultClass
          when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(mockResultClass);

          //calling MainClass method
          MainClass.someServiceMethod();
          }





          share|improve this answer
























            1












            1








            1






            You are not returning expected object while writing mock statement



                @Service
            public class C {
            @Autowired
            SomeRepository someRepository;
            public ResultClass getResult(string,string, int, int, List<String>,boolean){
            ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);

            //Your return type should be ResultClass
            // Where your return statement
            // What is ABC?
            }
            }

            @Test
            MainClassTest {
            @MockBean
            SomeRepository someRepository;
            when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);
            // Why are you returning SomeRepository, This Should return object of ABC

            @MockBean
            ABC mockResultClass
            when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(mockResultClass);

            //calling MainClass method
            MainClass.someServiceMethod();
            }





            share|improve this answer












            You are not returning expected object while writing mock statement



                @Service
            public class C {
            @Autowired
            SomeRepository someRepository;
            public ResultClass getResult(string,string, int, int, List<String>,boolean){
            ABC returnSomeClassObject = someRepository.getSomeData(String,int,int);

            //Your return type should be ResultClass
            // Where your return statement
            // What is ABC?
            }
            }

            @Test
            MainClassTest {
            @MockBean
            SomeRepository someRepository;
            when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(SomeRepository);
            // Why are you returning SomeRepository, This Should return object of ABC

            @MockBean
            ABC mockResultClass
            when(someRepository.getSomeData(anyString(),anyInt(),anyInt())).thenReturn(mockResultClass);

            //calling MainClass method
            MainClass.someServiceMethod();
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 27 '18 at 16:40









            Govind Parashar

            14619




            14619

























                1














                You are calling MainClass.someServiceMethod() which in turn calls getResult of class C. You should be mocking class C and using when-thenReturn on getResult() of C class if your intention is to test someServiceMethod() of Main class. Autowired will not work here since this is a Unit test and hence the instance of C c in Main class will be null.
                Something like below:



                @MockBean
                C c;
                when(c.getResult(anyString(), anyString(),anyInt(),anyInt(), any(List.class), anyBoolean()).thenReturn(someResult);

                c.getResult(string,string, int, int, List<String>,boolean);





                share|improve this answer




























                  1














                  You are calling MainClass.someServiceMethod() which in turn calls getResult of class C. You should be mocking class C and using when-thenReturn on getResult() of C class if your intention is to test someServiceMethod() of Main class. Autowired will not work here since this is a Unit test and hence the instance of C c in Main class will be null.
                  Something like below:



                  @MockBean
                  C c;
                  when(c.getResult(anyString(), anyString(),anyInt(),anyInt(), any(List.class), anyBoolean()).thenReturn(someResult);

                  c.getResult(string,string, int, int, List<String>,boolean);





                  share|improve this answer


























                    1












                    1








                    1






                    You are calling MainClass.someServiceMethod() which in turn calls getResult of class C. You should be mocking class C and using when-thenReturn on getResult() of C class if your intention is to test someServiceMethod() of Main class. Autowired will not work here since this is a Unit test and hence the instance of C c in Main class will be null.
                    Something like below:



                    @MockBean
                    C c;
                    when(c.getResult(anyString(), anyString(),anyInt(),anyInt(), any(List.class), anyBoolean()).thenReturn(someResult);

                    c.getResult(string,string, int, int, List<String>,boolean);





                    share|improve this answer














                    You are calling MainClass.someServiceMethod() which in turn calls getResult of class C. You should be mocking class C and using when-thenReturn on getResult() of C class if your intention is to test someServiceMethod() of Main class. Autowired will not work here since this is a Unit test and hence the instance of C c in Main class will be null.
                    Something like below:



                    @MockBean
                    C c;
                    when(c.getResult(anyString(), anyString(),anyInt(),anyInt(), any(List.class), anyBoolean()).thenReturn(someResult);

                    c.getResult(string,string, int, int, List<String>,boolean);






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 27 '18 at 16:48

























                    answered Dec 27 '18 at 16:42









                    Aditya Narayan Dixit

                    1,254412




                    1,254412























                        0














                        So, first of all, we need to be clear on what exactly you are unit testing. If you are trying to unit test someServiceMethod inside of MainClass, then that means you should NOT be also testing the functionality of someRepository. The idea is that each unit test should only be testing just that, a unit of code. So, to do that we need to use stubs as stand-ins for what would actually happen when you call methods owned by other classes. Then, we would write a differrent unit test just for someRepository.getSomeData() to confirm that it is also working as intended. In this manner, when get an error later down the line we will know exactly where we are encountering an issue.



                        Another issue I see is there is an apparent mismatch of return types for getResult() in C. The method says it returns a ResultClass, but when you call getSomeData you are expecting an ABC object. Either you left out the details where you convert the object back to a ResultClass, or that is a mistake. I'm going to assume the former unless you say otherwise.



                        With that in mind, let's write our test. Here's how I would write the test:



                        @RunWith(SpringRunner.class)
                        public class MainClassTest {

                        @Mock
                        C c;

                        @InjectMocks
                        MainClass mainClass;

                        @Test
                        public void testSomeServiceMethod {

                        ResultClass resultClass = new ResultClass(); //relevant constructor details here, mockbean, etc. you get the idea

                        //set any desired data for resultClass here

                        Mockito.when(c.getResult(anyString(), anyString(),
                        anyInt(), anyInt(), any(List.class), anyBoolean()))
                        .thenReturn(resultClass);

                        ResultClass newResult = mainClass.someServiceMethod();

                        //relevant test assertions here
                        }
                        }


                        As you can see, we are creating a ResultClass in the test, and telling Mockito to return that when getResult is called instead of what you would normally expect it to return. While the functionality may seem limited now, this is preferred as we only testing the MainClass and not the rest of our method calls.



                        In addition to this, we can (and should) write tests for getResult in C, and getSomeData in SomeRepository. I will leave it to you to write those tests.



                        EDIT: accidentally posted a bit early, fixing now.






                        share|improve this answer




























                          0














                          So, first of all, we need to be clear on what exactly you are unit testing. If you are trying to unit test someServiceMethod inside of MainClass, then that means you should NOT be also testing the functionality of someRepository. The idea is that each unit test should only be testing just that, a unit of code. So, to do that we need to use stubs as stand-ins for what would actually happen when you call methods owned by other classes. Then, we would write a differrent unit test just for someRepository.getSomeData() to confirm that it is also working as intended. In this manner, when get an error later down the line we will know exactly where we are encountering an issue.



                          Another issue I see is there is an apparent mismatch of return types for getResult() in C. The method says it returns a ResultClass, but when you call getSomeData you are expecting an ABC object. Either you left out the details where you convert the object back to a ResultClass, or that is a mistake. I'm going to assume the former unless you say otherwise.



                          With that in mind, let's write our test. Here's how I would write the test:



                          @RunWith(SpringRunner.class)
                          public class MainClassTest {

                          @Mock
                          C c;

                          @InjectMocks
                          MainClass mainClass;

                          @Test
                          public void testSomeServiceMethod {

                          ResultClass resultClass = new ResultClass(); //relevant constructor details here, mockbean, etc. you get the idea

                          //set any desired data for resultClass here

                          Mockito.when(c.getResult(anyString(), anyString(),
                          anyInt(), anyInt(), any(List.class), anyBoolean()))
                          .thenReturn(resultClass);

                          ResultClass newResult = mainClass.someServiceMethod();

                          //relevant test assertions here
                          }
                          }


                          As you can see, we are creating a ResultClass in the test, and telling Mockito to return that when getResult is called instead of what you would normally expect it to return. While the functionality may seem limited now, this is preferred as we only testing the MainClass and not the rest of our method calls.



                          In addition to this, we can (and should) write tests for getResult in C, and getSomeData in SomeRepository. I will leave it to you to write those tests.



                          EDIT: accidentally posted a bit early, fixing now.






                          share|improve this answer


























                            0












                            0








                            0






                            So, first of all, we need to be clear on what exactly you are unit testing. If you are trying to unit test someServiceMethod inside of MainClass, then that means you should NOT be also testing the functionality of someRepository. The idea is that each unit test should only be testing just that, a unit of code. So, to do that we need to use stubs as stand-ins for what would actually happen when you call methods owned by other classes. Then, we would write a differrent unit test just for someRepository.getSomeData() to confirm that it is also working as intended. In this manner, when get an error later down the line we will know exactly where we are encountering an issue.



                            Another issue I see is there is an apparent mismatch of return types for getResult() in C. The method says it returns a ResultClass, but when you call getSomeData you are expecting an ABC object. Either you left out the details where you convert the object back to a ResultClass, or that is a mistake. I'm going to assume the former unless you say otherwise.



                            With that in mind, let's write our test. Here's how I would write the test:



                            @RunWith(SpringRunner.class)
                            public class MainClassTest {

                            @Mock
                            C c;

                            @InjectMocks
                            MainClass mainClass;

                            @Test
                            public void testSomeServiceMethod {

                            ResultClass resultClass = new ResultClass(); //relevant constructor details here, mockbean, etc. you get the idea

                            //set any desired data for resultClass here

                            Mockito.when(c.getResult(anyString(), anyString(),
                            anyInt(), anyInt(), any(List.class), anyBoolean()))
                            .thenReturn(resultClass);

                            ResultClass newResult = mainClass.someServiceMethod();

                            //relevant test assertions here
                            }
                            }


                            As you can see, we are creating a ResultClass in the test, and telling Mockito to return that when getResult is called instead of what you would normally expect it to return. While the functionality may seem limited now, this is preferred as we only testing the MainClass and not the rest of our method calls.



                            In addition to this, we can (and should) write tests for getResult in C, and getSomeData in SomeRepository. I will leave it to you to write those tests.



                            EDIT: accidentally posted a bit early, fixing now.






                            share|improve this answer














                            So, first of all, we need to be clear on what exactly you are unit testing. If you are trying to unit test someServiceMethod inside of MainClass, then that means you should NOT be also testing the functionality of someRepository. The idea is that each unit test should only be testing just that, a unit of code. So, to do that we need to use stubs as stand-ins for what would actually happen when you call methods owned by other classes. Then, we would write a differrent unit test just for someRepository.getSomeData() to confirm that it is also working as intended. In this manner, when get an error later down the line we will know exactly where we are encountering an issue.



                            Another issue I see is there is an apparent mismatch of return types for getResult() in C. The method says it returns a ResultClass, but when you call getSomeData you are expecting an ABC object. Either you left out the details where you convert the object back to a ResultClass, or that is a mistake. I'm going to assume the former unless you say otherwise.



                            With that in mind, let's write our test. Here's how I would write the test:



                            @RunWith(SpringRunner.class)
                            public class MainClassTest {

                            @Mock
                            C c;

                            @InjectMocks
                            MainClass mainClass;

                            @Test
                            public void testSomeServiceMethod {

                            ResultClass resultClass = new ResultClass(); //relevant constructor details here, mockbean, etc. you get the idea

                            //set any desired data for resultClass here

                            Mockito.when(c.getResult(anyString(), anyString(),
                            anyInt(), anyInt(), any(List.class), anyBoolean()))
                            .thenReturn(resultClass);

                            ResultClass newResult = mainClass.someServiceMethod();

                            //relevant test assertions here
                            }
                            }


                            As you can see, we are creating a ResultClass in the test, and telling Mockito to return that when getResult is called instead of what you would normally expect it to return. While the functionality may seem limited now, this is preferred as we only testing the MainClass and not the rest of our method calls.



                            In addition to this, we can (and should) write tests for getResult in C, and getSomeData in SomeRepository. I will leave it to you to write those tests.



                            EDIT: accidentally posted a bit early, fixing now.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 27 '18 at 17:50

























                            answered Dec 27 '18 at 17:20









                            Stalemate Of Tuning

                            111110




                            111110






























                                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%2f53947954%2fgetting-nullpointerexception-while-calling-nested-method-of-service-class-using%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

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas