java123999 java123999 - 1 year ago 59
Java Question

Mockto: how to test that a constructor was called?

I am using

to test methods within my

How can I test that a constructor was called one?

I am trying to do a verify similar to this:

verify(myclass, times(1)).doSomething(anotherObject);

But I cant verify the constructor was called as it doesn't have a method similar to e.g. doSomething()

Answer Source

This can't be done with Mockito, since the object being created is not a mocked object. This also means that you won't be able to verify anything on that new object either.

I've worked around this scenario in the past by using a Factory to create the object rather than newing it up. You're then able to mock the Factory to return the object required for your test.

Whether you're happy changing your design to suit your tests is up to you!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download