Unit testing with mockito for constructors

后端 未结 7 1619
感动是毒
感动是毒 2020-11-28 07:36

I have one class.

Class First {

    private Second second;

    public First(int num, String str) {
        second = new Second(str);
        this.num = num         


        
7条回答
  •  半阙折子戏
    2020-11-28 08:03

    Once again the problem with unit-testing comes from manually creating objects using new operator. Consider passing already created Second instead:

    class First {
    
      private Second second;
    
      public First(int num, Second second) {
        this.second = second;
        this.num = num;
      }
    
      // some other methods...
    }
    

    I know this might mean major rewrite of your API, but there is no other way. Also this class doesn't have any sense:

    Mockito.when(new Second(any(String.class).thenReturn(null)));
    

    First of all Mockito can only mock methods, not constructors. Secondly, even if you could mock constructor, you are mocking constructor of just created object and never really doing anything with that object.

提交回复
热议问题