Create a Junit test case for a method which contains a call to another method from different class which calls to a different method of the same class

烂漫一生 提交于 2020-01-07 02:58:21

问题


I am new to java and Unit testing. I am facing a problem in writing a unit test to one of the test methods. Can you please help me with this.

ClassA:

Class   classA{ 
    /*......*/
    classB  method1_ClassA(parameters){
        /*.....
        .....
        .....
        .....
        .....*/
        String  some_Identifier =   method2_ClassA(parameters)

    }
    private String  method2_ClassA(parameters){
        /*contains call to the database*/
    }
}

ClassB:

Class classB{
    /*.....*/
}

ClassC:

Class   classC{
    /*.......*/
    public  classB  method1_ClassC(parameters){
            classA  obj_ClassA  =   new classA();
            return  obj_ClassA.method1_classA(parameters);
    }
    /*.......*/

}

I am trying to do Unit Testing to the classC. One of the methods in ClassC calls a method of class A. I tried to mock this method, which is method1_classA. But this method has a call to another method which is present in the same class. Can somebody please help me on how to create a unit test for classC.


回答1:


I think I am getting your problem by now. The problem is that you created untestable code. It is as simple as that:

class C {
  public B foo(parameters){
    A someA new A();
    return  someA.someMethod(parameters);

(please note: I reworked your example to use names that aren't so confusing for java programmers. You do not put "class" into the name of a class for example)

The problem with your code is that call to new. Simply spoken, that call makes it almost impossible to do reasonable unit testing for that method. The only reasonable answer here is: rework your production code, and introduce dependency injection, like

class C {
  private A someA;

  public C() { this(new A()); }
  C(A someA) { this.someA = someA; }

  public B foo(parameters){            
    return  someA.someMethod(parameters);

What you see there: there is an "internal" constructor that you can use to provided an A object. You use this constructor to give a mocked A to C; and all of a sudden, you can test the whole thing.

So, long story short:

a) I really advise to change this code; because it is badly designed, and simply not testable as of now

b) If you really can't do that; you might want to look if Powermock can help you here ... but beware: that is not a tool for beginners. It is powerful and dangerous on many levels.

In any case, watch this ...



来源:https://stackoverflow.com/questions/38484623/create-a-junit-test-case-for-a-method-which-contains-a-call-to-another-method-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!