简体   繁体   中英

JUnit - Mocking class used in tested methods

ie two classes:

class A{
  public int getValue(){
    return 5;
  }
}

class B{
  public int getValue(){
    A a = new A();
    return a.getValue();
  }
}

Now I want to write a test for class B , but I want to mock class A for that test. The question is: how?

(This snippet is only a simpler version of my problem, please don't take care returning 5 or smth)

Probably there are some tricky way to do so, but in brief, the way you write B does not favor mocking. Instead of instantiating A in B, try to inject A to B

Consider changing it to

class B {
  private A a;
  public void setA(A a) {
    this.a=a;
  }
  public int getValue(){
    return a.getValue();
  }
}

You can even initialize a by private A a = new A() , but providing a setter allow you to inject a mock for testing.


Edit: If there are difficulties in rewriting B to make it unit test friendly, you still can make use of mocking framework that will do bytecode manipulation, like Powermock. Here is an example of achieving what you want:

http://code.google.com/p/powermock/wiki/MockConstructor

Mocking can be done using instance variable and have a setter for the same.

Below two links possibly help you to the above things you are trying to do

JUnit mocking with Mockito, EasyMock, etc How to mock local variables in java?

Mock class use to get data which required to test other class functionality. In this case no use of mock class for class A since it just returning 5. but if it is business logic inside class A, you should use a mock class. create a new class and add same method names in original class and without doing any logic just return some value from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM