how to mock an instance method invocation from static method while writing junit for static method? - junit

how to mock an instance method invocation from static method while writing junit for static method?I'm writing tests for existing code.
class A
{
public static D methodX()
{
B b = new B();
C c = b.doSomething();
}
}
class B
{
public C doSomething()
{
return C;
}
}
class Atest
{
#Test
public void testMethodX()
{
B b =Mockito.mock(B.class);
Mockito.when(b.doSomething()).thenReturn(new C());
A.methodX();
// some assertions
}
}

By your tag selection you already know that you need to go for PowerMockito.
In order to inject a mocked version of B class i would do the following:
A class
class A
{
public static D methodX()
{
B b = getBInstance();
C c = b.doSomething();
}
static B getBInstance(){
return new B();
}
}
Test Class
#RunWith(PowerMockRunner.class)
#PrepareForTest(A.class)
class Atest
{
#Test
public void testMethodX()
{
B b =Mockito.mock(B.class);
PowerMockito.stub(PowerMockito.method(A.class, "getBInstance")).toReturn(b);
Mockito.when(b.doSomething()).thenReturn(new C());
A.methodX();
// some assertions
}
}
Thanks to PowerMockito.stub(PowerMockito.method call you will just mock the getBInstance static method and in the end call the real A.methodX implementation.

Another completely different approach: do not write un-testable code. static is an abnormality within good OO designs; to the first step is to simply not write static methods.
And when you have good reasons to still do so; then write them in a way that allows you reasonable unit-test them.
Yes, it is possible to turn to PowerMock(ito) to get this solved, but the more sane approach is to simple fix your production design.
The PowerMock(ito) frameworks come at certain cost; and can easily be avoided.
Thus, my answer: learn how to create testable code; and simply forget about PowerMock (you can start by watching these videos).

Related

Mocking call to static method call inside spy method

Pretty new to mockito. Stuck with a basic thing:
#Override
public void updateMeeting(Meeting meeting, Meeting oldMeeting, List<MeetingOccurrence> oldMeetingOccurrences, List<MeetingOccurrence> newMeetingOccurrences) {
Predicate<Meeting> update = (e) -> MeetingUtil.needReminderChange(oldMeeting, meeting, oldMeetingOccurrences, newMeetingOccurrences);
// DO STUFF
if(ConfUtil.isRecurrenceMeeting(meeting.getType()) && meeting.getType() == oldMeeting.getType()){
update = update.or((e) -> recurringMeetingDurationChange(oldMeetingOccurrences, newMeetingOccurrences));
}
}
if (update.test(meeting)) {
sendEvent(meeting, MeetingConstants.MTG_CHANGE_EVEN_TYPE_UPDATE, getNotifiers(meeting, oldMeeting));
}
}
//---
TEST CLASS
public void testUpdateMeeting(){
MeetingNotifyService meetingNotifyService = Mockito.spy(MeetingNotifyServiceImpl.class);
Meeting meeting = Mockito.spy(Meeting.class);
Meeting oldMeeting = Mockito.spy(Meeting.class);
meeting.setType(Constants.MTG_TYPE_RECURRENCE);
meetingNotifyService.updateMeeting(meeting,oldMeeting,null,null);
}
//--
Problem is that when the code hits this line: ConfUtil.isRecurrenceMeeting it fails. It happens because of static block code inside ConfUtil. How can I tell mockito to not actually call ConfUtil.isRecurrenceMeeting and just return true. I cannot use powermockito
You can use PowerMockito to mock the static method. But the best way I would suggest you to avoid PowerMockito and have your code designed as testable code. So you don't have to mock a static method, consider to have it as a singleton service and you just have to mock a service normally.

How to capture constructor arguments using PowerMockito

class A {
public B getB(){
// somehow get argType1 and argType2
return new B(argType1, argType2);
}
}
class B{
public B(Type1 t1, Type2 t2){
// something
}
}
I want to Test A, and verify that constructor of B is getting called for expected values of argType1 and argType2.
How can i do this using PowerMockito?
Is there a way to pass argumentCaptor like this:
whenNew(B.class).withArguments(argType1Captor, argType2Captor).thenReturn(somemock);
if this do this, argType1Captor gets both the values
I solved it by doing this
PowerMockito,verifyNew(B.class).withArgument(expectedArgType1, expectedArgType2)
Dhrumil Upadhyaya, your answer (admittedly the only one offered) doesn't solve the question you asked! I think you might want to do something like:
public class MyTest {
private ArgType argument;
#Before
public void setUp() throws Exception {
MyClass c = mock(MyClass.class);
whenNew(MyClass.class).withAnyArguments()
.then((Answer<MyClass>) invocationOnMock -> {
argument = (ArgType) invocationOnMock.getArguments()[0];
return c;
}
);
}
}
It's not an elegant solution but it will capture the argument(s) passed to the constructor. The advantage over your solution is that if argument is a DTO then you can inspect it to see if it contains the values you were expecting.

How to check that a List contains only certain unrelated class types using junit's assertThat?

Would appreciate some help with hamcrest and junit matchers... :)
I'm using junit-4.11.jar and hamcrest-core-1.3.jar on Eclipse Kepler with sun's jdk 1.6.0_30.
I have a class that holds an instance of any unknown type like so:
class UnknownClassHolder {
private Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
clazz can be any class.
I want to my junit test to be something like this:
class UnknownClassHolderTest {
#Test
public void test() {
ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
UnknownClassHolder x = new UnknownClassHolder();
//lets add an Integer
x.setClazz(Integer.class);
list.add(x);
UnknownClassHolder y = new UnknownClassHolder();
//lets add a vector
y.setClazz(Vector.class);
list.add(y);
//now check that we added an Integer or a Vector using assertThat
for (UnknownClassHolder u: list) {
assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
}
}
}
Junit's assertThat doesn't like this. It doesn't compile due to Integer & Vector Types not being related to each other via sub/super classes:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)
Is there a more succinct way to do this other than:
assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));
Is there a particular reason for using Matcher<? super T> rather than Matcher<?> in the org.hamcrest.MatcherAssert.assertThat(...) method?
Thanks.
First, you should be using is instead of isA since you're asserting that one class equals another. isA is for testing that an object is an instance of some class. Second, the only thing I can make work is forcing the compiler to see these as raw Objects.
assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

doing a verify on void method using powerMock

There is a local instance of a class being instantiated inside a method.
eg
class TestMe{
public void foo()
{
A a = new A();
a.setState(this);
}
}
class A
{
private B b;
public void setState(TestMe tm)
{
b.doSomething(); //returns void
b.doSomethingAdditional(); //returns void
}
}
When testing foo, using powerMock, I wanted to do a verify to ensure that methods doSomething() and doSomethingAdditional() are called. I was looking something along the lines of the Mockito.verify(ObjectName).functionName() to do. Any suggestions??
PowerMock works in combination with Mockito. You should still have all the functionality to verify using Mockito calls.
Once you mock B, when you mock its functions and then pass it into A you can use the Mockito.verify.
verify(mockBObject).doSomething();
verify(mockBObject).doSomethingAdditional();
This may need a few extra steps to hook your mock object into A, since you don't have a constructor where you can define B passed in, or have some constructor to hook into. If you are just having A initialize B at the creation of A, you can use some PowerMockito tools to tell it what to do. Just mocking B will not do, because when your A is setup, it doesn't know to use your mocked object in its code as the B internal.
PowerMockito.whenNew(B.class).withNoArguments().thenReturn(mockBObject);
As of right now B is never setup or initialized, so it could cause some issues. If B is a static singleton object that you are assuming is created somewhere else, you can do similar mocking of the static getInstance() call to return a mock of B.

Language Agnostic Basic Programming Question

This is very basic question from programming point of view but as I am in learning phase, I thought I would better ask this question rather than having a misunderstanding or narrow knowledge about the topic.
So do excuse me if somehow I mess it up.
Question:
Let's say I have class A,B,C and D now class A has some piece of code which I need to have in class B,C and D so I am extending class A in class B, class C, and class D
Now how can I access the function of class A in other classes, do I need to create an object of class A and than access the function of class A or as am extending A in other classes than I can internally call the function using this parameter.
If possible I would really appreciate if someone can explain this concept with code sample explaining how the logic flows.
Note
Example in Java, PHP and .Net would be appreciated.
Let's forget about C and D because they are the same as B. If class B extends class A, then objects of type B are also objects of type A. Whenever you create an object of type B you are also creating an object of type A. It should have access to all of the methods and data in A (except those marked as private, if your language supports access modifiers) and they can be referred to directly. If B overrides some functionality of A, then usually the language provides a facility to call the base class implementation (base.Foo() or some such).
Inheritance Example: C#
public class A
{
public void Foo() { }
public virtual void Baz() { }
}
public class B : A // B extends A
{
public void Bar()
{
this.Foo(); // Foo comes from A
}
public override void Baz() // a new Baz
{
base.Baz(); // A's Baz
this.Bar(); // more stuff
}
}
If, on the other hand, you have used composition instead of inheritance and B contains an instance of A as a class variable, then you would need to create an object of A and reference it's (public) functionality through that instance.
Composition Example: C#
public class B // use A from above
{
private A MyA { get; set; }
public B()
{
this.MyA = new A();
}
public void Bar()
{
this.MyA.Foo(); // call MyA's Foo()
}
}
depending on the access level (would be protected or public in .NET), you can use something like:
base.method(argumentlist);
the base keyword in my example is specific to C#
there is no need for an instance of class A, because you already have a class A inherited instance
Basically you need a reference to the parent class.
In PHP:
parent::example();
From: http://www.php.net/manual/en/keyword.parent.php
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
I find that the best way to tame the complexity of inheritance is to ensure that I only make B inherit from A when it really is a specialization of the superclass. At that point, I can call A's methods from inside B just as if they were B's own methods, and if B has overridden them then I can only suppose that this must be for a good reason.
Of course, quite often it is useful for B's implementation of a method to invoke A's implementation on the same object, generally because the subclass is wrapping extra behavior around the superclass's basic definition. The way in which you do this varies between languages; for example, in Java you do this:
super.methodName(arg1, ...);
Here's a quick Java example:
public class Aclass
{
public static void list_examples()
{
return("A + B = C");
}
}
public class Bclass extends Aclass
{
public static void main(String [] args)
{
System.out.println("Example of inheritance "+list_examples);
}
}
Note that the method for accessing the parent class shouldn't change. Because you are extending you shouldn't have to say parent:: or anything unless you are overriding the parent method / function.
It seems to me that extending your class might not be your best option. Class "B", "C", and "D" should only extend class "A" if they are truly an extension of that class, not just to access some method. For instance "Huffy" should not extend "BrandNames" just because "Huffy" is a brand name and you want access to one of the methods of "BrandNames". "Huffy" should instead extend "Bicycle" and implement an interface so the methods of "BrandNames" can be used. An additional benefit here is that (in Java) multiple interfaces can be used but a class can only be extended once. If in your example class "B"' needed to access a method from class "A" that could work, but if class "C" needed to access a method from class "A" and class "'B"' then you would have to use an interface in class "'C".