1

I have a basic question with regards to unit testing. I believe when you unit test , you basically test a unit of code and in case of java , we could treat each method as a unit of code. I believe when we unit test a method , all the calls to another method must be mocked in order to test the functionality of the method. Below is an exmaple. Please let me know if my understanding is correct.

I have classes A , B and C

Class A has method 1

Class B has method 1 and 2

Class C has method 1 which makes an external service call.

Class A.method 1-> Class B.method1 -> ClassB.method2 -> Class C.method 1 -> external soap service.

In the above scenario when I am unit testing Class A method 1 , should I mock the Class B.method1 response? Similarly when I am unit testing Class B.method1 , should mock Class B.method 2? I believe this would apply to other methods which are being called subsequently as well.

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315
  • I saw your question got downvoted. Probably because it is not really related to Spring Boot but more a general Unit Testing question and ppl considered it misleading? – Tony Lang Sep 23 '16 at 15:58
  • @TonyLang Someone downvoted about 10 of my posts in last 10 minutes. They are even downvoting the answers for my questions. – Punter Vicky Sep 23 '16 at 16:08
  • @PaulSweatte , the link that you posted seems to talk about integration tests. – Punter Vicky Sep 23 '16 at 16:43

1 Answers1

1

"when I am unit testing Class A method 1 , should I mock the Class B.method1"

I think so, because you are testing Class A as the "unit"

"when I am unit testing Class B.method1 , should mock Class B.method 2"

You can but maybe you won't want to.

If B.method2 is private, it is part of the logic B.method1

If B.method2 is public, the fact that B.method1 calls it might indicate that method can be separated into another class because method1 and method2 might not be in the abstract level.

And if you do want to mock B.method2 when testing B.method1, you can use spy.

Community
  • 1
  • 1
Tony Lang
  • 170
  • 1
  • 9