如何使用 Iterator 覆盖 While 块并使用 mockito 和 Junit4 捕获方法?

问题描述

我必须介绍一下 Junit4 和 Mockito/powermockito 的 While 块和 catch 块。 Exception StateException 由 getHrest 方法启动

public class Fstate{
 ….
private Date selectedDate;
private Date dateYes;
private Collection<State> sstateList;
private boolean statePlus;
private String stateVisibility;

@EJB
private Muller mull;
….
public void methodState(){
    final Calendar calendar=new GregorianCalendar();
    this.dateYes=calendar.getTime();
    this.selectedDate = this.dateYes;
    Collection<State> allState=null;
    try{
        allState=this.mull.getHrest(this.p,this.b,this.ba,this.so);
        Iterator<State> iter=allState.iterator();
        while(iter.hasNext()){
            State s=iter.next();
            String s_string=s.getSfielString(); 
            this.sstateList.add(s_string);
        }
     } catch (StateException stateException){
        WebLogger.fatal(stateException.getMessage(),LOGGER_OUT);
    }
    this.statePlus=loadStatePlus(this.dateYes);
    this.stateVisibility=STATE_PLUS;
}
}

下面,在第一种方法中,我想覆盖 while 执行,而在第二种方法中,我想覆盖捕获。 然而,这并没有产生预期的结果,而block和catch没有覆盖!

@Test
public void state_test(){
    try {
    
        Fstate spyFstate = Mockito.spy(Fstate.class);
        
        State mockState=Mockito.mock(Muller.class);     
        
        Mockito.when(mockState.getHrest(anyString(),anyString(),anyString())).thenReturn(createCollectionOfStates());
        WhiteBox.setInternalState(spyFstate,"mull",mockState);
        
        spyFstate.methodState();
        Mockito.verify(spyFstate,Mockito.times(1)).methodState();
        
    } catch (StateException e) {
        System.out.println("StateException in state_Test method!");
    }
}
    
@Test
public void stateException_test(){
    try {
            Fstate spyFstate = Mockito.spy(Fstate.class);
            
            State mockState=Mockito.mock(Muller.class); 
    
            Mockito.when(mockState.getHrest(anyString(),anyString())).thenThrow(new StateException("StateException Exception"));
            
            WhiteBox.setInternalState(spyFstate,mockState);
            spyFstate.methodState();
            
            Mockito.verify(spyFstate,Mockito.times(1)).methodState();
            
    } catch (DealAnagException e) {
            e.printstacktrace();
    }   
}

解决方法

我认为你只需要在像这样创建你的间谍之前实例化你的 Fstate :

Fstate fstate = new Fstate();
Fstate spyFstate = Mockito.spy(fstate);