Unit testing with mockito for constructors

后端 未结 7 1584
感动是毒
感动是毒 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:14

    I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach

    Class First {
    
       private Second second;
    
       public First(int num, String str) {
         if(second== null)
         {
           //when junit runs, you get the mocked object(not null), hence don't 
           //initialize            
           second = new Second(str);
         }
         this.num = num;
       }
    
       ... // some other methods
    }
    

    And, for test:

    class TestFirst{
        @InjectMock
        First first;//inject mock the real testable class
        @Mock
        Second second
    
        testMethod(){
    
            //now you can play around with any method of the Second class using its 
            //mocked object(second),like:
            when(second.getSomething(String.class)).thenReturn(null);
        }
    }
    
    0 讨论(0)
提交回复
热议问题