Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with mockito for constructors

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?

like image 574
Tarun Kumar Avatar asked Jun 26 '12 18:06

Tarun Kumar


People also ask

Can I mock a constructor using Mockito?

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.

How do you unit test a constructor?

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.

How do you call a mock method in a constructor?

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.

Is Mockito used for unit testing?

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.


1 Answers

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.

like image 127
terma Avatar answered Sep 22 '22 07:09

terma