微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。