How to mock new variable of a class

2,975 views
Skip to first unread message

Jitu

unread,
Aug 10, 2011, 12:33:00 AM8/10/11
to mockito
I want to test class A ..how to write JUnit for this ..


Class A{


B b = new B(); //Variable of class A

public String method(parameter) //method of class A
{
String str = b.method2();
return str;

}

}

Simon Brunning

unread,
Aug 10, 2011, 3:19:17 AM8/10/11
to moc...@googlegroups.com

Instead of newing up B in your class, either inject it, or a factory. An IOC approach like this doesn't only make testing simpler - I find it makes complex systems with many components easier to work with.

Cheers,
Simon B.

Vishwanath Krishnamurthi

unread,
Aug 10, 2011, 3:17:18 AM8/10/11
to moc...@googlegroups.com
The class A as such is not testable. That's because, the collaborator B is created with the new operator.
Instead if the creation is done somewhere else, and the dependency was injected, then the class would be testable.

Here's how it might look

I find this blog http://misko.hevery.com/ to be extremely useful to understand 'testability'.

HTH,
Vishwa


--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


Szczepan Faber

unread,
Aug 10, 2011, 9:47:26 AM8/10/11
to moc...@googlegroups.com
Good hints. Generally, first read about dependency injection then you'll immediately understand what the mocks are for :)

Cheers!
--
Szczepan Faber
Principal engineer@gradleware
Lead@mockito
Reply all
Reply to author
Forward
0 new messages