52

What is the difference between the @SpyBean and @MockBean annotations in Spring?

I have already gone through the JavaDoc but didn't get the difference. If possible please give an example when to use MockBean and when SpyBean.

Saikat
  • 14,222
  • 20
  • 104
  • 125
Vikrant Chaudhary
  • 629
  • 1
  • 7
  • 12

1 Answers1

114

A mock (no matter if we talk about ordinary objects or beans) is simply an "empty shell".

That mock object doesn't have any relation to the underlying production code. It is an object that looks like being an object of class X. But none of the methods or fields that X has do "really" exist on that mocked thing.

Whereas a spy wraps around an existing object of your class under test. Meaning: when you create a spy, you can decide if method calls going to the spy should be "intercepted" (then you are using the spy as if it would be a mock); or be "passed through" to the actual object the spy wraps around.

See here for further reading.

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks but couldn't get a clear idea. Can you elaborate more why spybean is like partial mockbean what is limitation of spybean? – Vikrant Chaudhary May 18 '17 at 10:05
  • 2
    Point is: this is documented all over the place. Simply read thee link I provided; or that other link I just added. A *spy* is more than a *mock*, so if at all, the mock is "limited" here. I hope this is enough to make my answer acceptable ... as said: don't expect me to repeat descriptions that are documented in many many places already. – GhostCat May 18 '17 at 10:47
  • 1
    @gstackoverflow Sorry, I can't help here. We are writing all our tests the same way, and just recently moved to JUnit5 ... never came across that error ;-( – GhostCat Aug 02 '21 at 09:21
  • @Ewoks Thanks. Obviously, that link is broken now. I simply removed it from the answer. – GhostCat Jul 18 '22 at 12:09