java 如何正确测试带有自定义异常的compareTo()方法?

carvr3hs  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(210)

使用自定义异常测试compareTo()方法时遇到问题。如何在没有编译错误的情况下抛出自定义异常?
Junit测试代码

@Test
    public void compareTo() {
        // check equals
        assertEquals(0, competitionDressageQualifier.compareTo(competitionDressageQualifier));
        try {
            Competition c1 = new Competition(competitionDressageQualifier.getEvent(), competitionDressageQualifier.getCompetitionDate(),
                    competitionDressageQualifier.getJudges(), competitionDressageQualifier.getCompetitionLevel());
            assertEquals(0, c1.compareTo(competitionDressageQualifier));
            assertEquals(0, competitionDressageQualifier.compareTo(c1));
        } catch (OlympicException ex) { //I HAVE THE ERROR HERE Unreachable catch block for OlympicException. This exception is never thrown from the try statement body
            // this shouldn't happen
            fail();
        }

compareTo()的代码,我如何在这里实现try catch?

@Override
    public int compareTo(Competition o) //compare properties
    {
        
        if(!Objects.equals(this.getCompetitionDate(), o.getCompetitionDate())) //first date
        {
            return (this.getCompetitionDate().compareTo(o.getCompetitionDate()));
        }
        
        else
        {
            if(!Objects.equals(this.competitionlevel, o.competitionlevel)) //seconds comp level
            {
                return (this.competitionlevel.compareTo(o.competitionlevel));
            }
            else
            {
            
                    if(!Objects.equals(this.getEvent().getEventName(), o.getEvent().getEventName())) //third priority is event name
                    {
                        return (this.getEvent().getEventName().compareTo(o.getEvent().getEventName()));
                    }
                
            }
        }       
        return 0; //if same return 0
    }

自定义异常代码:

public class OlympicException extends Exception {

    private long serialVersionUID=-1;
   
    public OlympicException()
       {
          // TODO Auto-generated constructor stub
       }

       public OlympicException( String s )
       {
          super( s );
          // TODO Auto-generated constructor stub
       }

       public OlympicException( Throwable cause )
       {
          super( cause );
          // TODO Auto-generated constructor stub
       }

       public OlympicException( String s, Throwable cause )
       {
          super( s, cause );
          // TODO Auto-generated constructor stub
       }

}

无论我尝试什么,我都会得到编译错误,我是否以错误的方式比较了一些东西?

7z5jn7bk

7z5jn7bk1#

将其设置为RuntimeException

public class OlympicException extends RuntimeException {

这将修复编译错误,并允许compareTo() impl抛出它。

相关问题