Test that Program Shutdown Successfully (or Not)?

671 views
Skip to first unread message

Kevin Meredith

unread,
Dec 13, 2015, 6:45:37 PM12/13/15
to scalatest-users
How can I test that a program shutdown successfully or not?

Example:

def f: Unit = {
  sys.exit(1)
}

How could I write a scalatest test that would test that calling `f` resulted in a shutdown with an exit code of 1 (or simply shutdown in a failed state)?

Bill Venners

unread,
Dec 14, 2015, 1:06:43 AM12/14/15
to scalate...@googlegroups.com
Hi Kevin,

Hmm. If you can decide on the signature of f, you could pass in an Exiter trait that in real code calls System.exit(code), somethin glike:

trait Exiter {
  def exit(code: Int): Unit
}

In a test you could make a MockExiter that just sets a flag and test that.

class MockExiter extends Exiter {
  var exitCode: Option[Int] = None
  def exit(code: Int): Unit = {
    exitCode = Some(code)
  }
}

If you want to test the real thing, or if you can't change the signature of f, then I perhaps you can use the Java API for forking (in java.lang.Runtime). You'd need to fork off another process from your test, then wait for it to complete, then look at its status. It wouldn't necessarily mean that *your* method did that, but you could check for that expected exit status. That's quite heavyweight to create another process, but you can do it.

Otherwise I think it is tough to capture whether or not something exited. Anyone else have any other ideas?

Bill

--
You received this message because you are subscribed to the Google
Groups "scalatest-users" group.
To post to this group, send email to scalate...@googlegroups.com
To unsubscribe from this group, send email to
scalatest-use...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/scalatest-users?hl=en
ScalaTest itself, and documentation, is available here:
http://www.artima.com/scalatest
---
You received this message because you are subscribed to the Google Groups "scalatest-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatest-use...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Bill Venners
Artima, Inc.
http://www.artima.com

Patrick T

unread,
Dec 14, 2015, 5:06:40 PM12/14/15
to scalatest-users

Otherwise I think it is tough to capture whether or not something exited. Anyone else have any other ideas?

You could install a custom security manager to trap System.exit(). Not sure if you can get access to the exit code, though.
See for example:
http://stackoverflow.com/questions/23741797/allow-system-exit-only-for-certain-classes
http://stackoverflow.com/questions/5401281/preventing-system-exit-from-api

Patrick
Reply all
Reply to author
Forward
0 new messages