I have one class.
Class First { private Second second; public First(int num, String str) { second = new Second(str); this.num = num; } ... // some other methods }
I want to write unit tests for public methods of class First. I want to avoid execution of constructor of class Second.
I did this:
Second second = Mockito.mock(Second.class); Mockito.when(new Second(any(String.class))).thenReturn(null); First first = new First(null, null);
It is still calling constructor of class Second. How can i avoid it?
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
To test that a constructor does its job (of making the class invariant true), you have to first use the constructor in creating a new object and then test that every field of the object has the correct value. Yes, you need need an assertEquals call for each field.
Faking static methods called in a constructor is possible like any other call. if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor.
Mockito is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.
You can use PowerMockito
See the example:
Second second = Mockito.mock(Second.class); whenNew(Second.class).withNoArguments().thenReturn(second);
But re-factoring is better decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With