简体   繁体   中英

How to output more than one string in junit

I have a list of messages which I compare with a given count. When the count fails then I want to output all messages found so I know which message is missing or superfluous. Currently I use:

     import scala.collection.JavaConversions._

     def Assert_Messages (
        expected : Int,
        actual   : java.util.List [String])
     {
        if (expected != 0 && actual.size == 0)
        {
           junit.framework.Assert.fail ("An expected error message was not reported.")
        }
        else if (expected != actual.size)
        {
           actual foreach (junit.framework.Assert.fail (_))
        } // if
     } // Assert_Messages

But this will only output the first message as junit.framework.Assert.fail does not return. Has anybody got an idea for me which does not involve an ugly StringBuffer?

JUnit is set as the test must run on Android.

Thanks for any help. I look forward to learning something new and nifty.

You can try junit.framework.Assert.fail(actual.mkString("; ")) . Replace "; " with whatever you want to use as separator; if you want to be able to reconstruct the original sequence of strings, be sure to escape characters that collide with your separating string, eg with a backslash or something.

Some side remarks:

  • it may not matter much in this particular case, but instead of checking someCollection.size == 0 , it is good practice to test for someCollection.isEmpty instead. On a Scala List , size is an O( n ) operation if n is the size of your list; isEmpty is O(1).
  • You don't need to explicitly write the scala. prefix when you import stuff from within the scala package (unless there are ambiguities), so import collection.JavaConversions._ will do nicely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM