Home > Software engineering >  Want to mock a method which is calling another class method
Want to mock a method which is calling another class method

Time:08-07

I am new to mockito using it for unit testing. I need some help to understand mock a method.I have a method - method1() of class A which needs to be tested .Here i want to verify that execute() is executed (Interaction testing).Below is the method.

class A{
void method1(){

  B b = new B(org_id);

  b.execute();


 }
}

 Class B {
    B(String orgId){
    this.orgId = org_id;
    }
    
    void execute(){
     String x = Dependency.m1();
    
     String y = Dependency.m2();
    
     }
    
     static class Dependency{
    
     public String m1(){

       return K.someText();

      }
    
     public String m2(){

      return K.someText();

     }
    }
   }

Could anyone help me how to achieve it?TIA

CodePudding user response:

As here you are not using any dependency injection, you cannot mock and inject that object into the test class using mocikto. You can look at this answer here :- Java Mock object, without dependency injection

CodePudding user response:

Make B an instance variable of A, add a constructor for A, pass the mock to constructor.

class A{
B b;
public A(B b){
  this.b = b;
 }
}

in test class

A a = new A(Mockito.mock(B.class));

CodePudding user response:

Since you create a new instance of B, you could parameterize A with a Function<String, B> (a factory method, or just B::new which you can the mock in your test.

class A {
 final Function<String, B> bCreator;
 A(Function<String, B> bCreator) {
   this.bCreator = bCreator;
 }
 void method1(){
  B b = bCreator.apply(orgId);
  b.execute();
 }
}

// test
B b = mock(B.class);
Function<String, B> bCreator = mock(Function.class);
when(bCreator.apply(any()).thenReturn(b);
A a = new A(bCreator);
a.method1();
verify(b).execute();

The test whether B::execute works correctly (ie calls the appropriate dependency methods) should be done in another test since it's another unit.

  • Related