I have this test classes:
class PostIT {
companion object {
#BeforeClass
#JvmStatic
fun initialise() {
baseURI = "http://localhost:4567"
Server.start()
}
#AfterClass
#JvmStatic
fun tearDown() {
Server.stop()
}
}
//some test cases
}
class UserIT {
companion object {
#BeforeClass
#JvmStatic
fun initialise() {
baseURI = "http://localhost:4567"
Server.start()
}
#AfterClass
#JvmStatic
fun tearDown() {
Server.stop()
}
}
//some test cases
}
and Server object:
object Server {
fun start() {
Spark.init()
prepareRoutes()
}
fun stop() {
Spark.stop()
}
private fun prepareRoutes() {
get("/users", whatever)
//more routes
}
}
When I run both test classes separately, it works fine. But, when I tell IDE to run both test classes, I'm getting connection refused error when second test class is run.
It seems like when server is stopped, it never starts again. It's like Spark.init() is not working after server being stopped.
I've also tried calling Spark.awaitInitialization() after Spark.init().
What am I missing?
Solved! Actually, problem wasn't the server initialization after stopped. We must wait until server is stopped. I found the solution here.
fun stop() {
try {
Spark.stop()
while (true) {
try {
Spark.port()
Thread.sleep(500)
} catch (ignored: IllegalStateException) {
break
}
}
} catch (ex: Exception) {
}
}
Related
How do I re throw the exception returned from remote call to caller method of handle function ?
suspend fun handle(phMessages: List<PrincipalHierarchyMessage>) {
val messageChannel = Channel<PrincipalHierarchyMessage>()
launchSender(phMessages, messageChannel).invokeOnCompletion {
messageChannel.close()
}
repeat(concurrency) { launchReceiver(messageChannel) }
}
private fun launchSender(phMessages: List<PrincipalHierarchyMessage>, channel: SendChannel<PrincipalHierarchyMessage>) = launch {
phMessages.forEach {
channel.send(it)
}
}
private fun launchReceiver(channel: ReceiveChannel<PrincipalHierarchyMessage>) = launch {
for (msg in channel) {
if (msg.isAddUserToGroup()) {
permsWriterClient.addUserToGroup(msg.groupId, msg.userId, msg.traceId, msg.isLowPriority)
} else if (msg.isRemoveUserFromGroup()) {
permsWriterClient.removeUserFromGroup(msg.groupId, msg.userId, msg.traceId, msg.isLowPriority)
} else {
// log
}
}
}
I have tried calling handle method from a coroutineScope inside try catch, where I expected to catch the exception, but it did not work
I'm trying to understand exception handling in Kotlin coroutines, so I came up with this very simple scenario where a network call throws an exception and my app has to catch it and handle it.
If I surround my async.await() call with a try-catch block, it works as intended. However, if I try to abstract that try-catch into an extension function, my app crashes.
What am I missing here?
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class Main2Activity : AppCompatActivity() {
private val job: Job = Job()
private val scope = CoroutineScope(Dispatchers.Default + job)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
runCode()
}
private suspend fun asyncCallThrowsException(): Deferred<Boolean> =
withContext(Dispatchers.IO) {
Thread.sleep(3000)// simulates a blocking request/response (not on the Main thread, though)
throw(Exception())
}
suspend fun <T> Deferred<T>.awaitAndCatch() {
try {
this.await()
} catch (e: Exception) {
println("exception caught inside awaitAndCatch")
}
}
private fun runCode() {
scope.launch {
//This block catches the exception.
try {
val resultDeferred = asyncCallThrowsException()
resultDeferred.await()
} catch (e: Exception) {
println("exception caught inside try-catch")
}
//This line does not, and crashes my app.
asyncCallThrowsException().awaitAndCatch()
}
}
}
Edit: I had actually forgotten to wrap the call inside an async block. Now, not even the explicit try-catch block works...
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class Main4Activity : AppCompatActivity() {
private val job: Job = Job()
private val scope = CoroutineScope(Dispatchers.Default + job)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runCode()
}
private suspend fun callThrowsException(): String =
withContext(Dispatchers.IO) {
Thread.sleep(3000)// simulates a blocking request/response (not on the Main thread, though)
throw(Exception())
"my result"
}
suspend fun <T> Deferred<T>.awaitAndCatch(): T? {
try {
return this.await()
} catch (e: Exception) {
println("exception caught inside awaitAndCatch")
}
return null
}
private fun runCode() {
scope.launch {
val resultDeferred: Deferred<String> = async { callThrowsException() }
var result: String?
// This doesn't catch the throwable, and my app crashes - but the message gets printed to the console.
try {
result = resultDeferred.await()
} catch (e: Exception) {
println("exception caught inside try-catch")
}
// This doesn't catch the throwable, and my app crashes - but the message gets printed to the console.
result = resultDeferred.awaitAndCatch()
}
}
}
The problem doesn't have to do with how you're catching the exception. The problem is that when your async job fails (throws the exception), it cancels the job you made for your activity.
Even though your code can catch the exception and print the message, the parent job will be terminated ASAP.
Instead of making it like this: val: Job = Job(), try val: Job = SupervisorJob()
A supervisor job isn't cancelled when its children fail, so this won't crash your app.
Or, if you want a way to start an async job that doesn't have this problem, see: Safe async in a given scope
To get to a correct solution, the problem to solve is making it compatible with the principles of structured concurrency.
What exactly is your motivation to use async? What do you plan to do in the meantime, between launching the async and awaiting on it?
If both the async launch and the await call are a part of a single unit of work, and the success of the async call is a prerequisite to the overall success, then wrap the entire unit of work in coroutineScope.
If you want to launch this task in the background and await on it from an Android callback that is invoked later on, then this can't be encapsulated into a single unit of work. You should attach the async task to the top-level CoroutineScope, which should have a SupervisorJob in it.
The proper way to do this is shown in the documentation of CoroutineScope:
class MyActivity : AppCompatActivity(), CoroutineScope by MainScope() {
override fun onDestroy() {
cancel() // cancel is extension on CoroutineScope
}
...
}
Kotlin standard library added the MainScope() delegate as a convenience so you don't get this wrong.
Please, help me write a JUnit test for this code using Mockito.
class A{
private BlockingQueue<Runnable> jobQueue;
public void methodA(List<String> messages) {
try {
jobQueue.put(() -> methodB(message));
} catch(InterruptedException e) {}
}
private void methodB(Message message) {
//other logic
}
}
Your example lacks context as to what it is methodB is doing... Without knowing what the functionality is that you want to verify, just verifying that methodB gets called wouldn't be a particularly useful test, nor is mocking the BlockingQueue. I'm going to go out on a limb and assume that methodB interacts with another object, and it's this interaction that you really want to verify, if that's the case my code and test would look something like:
class A {
private BlockingQueue<Runnable> jobQueue;
private B b;
public void methodA(Message message) {
try {
jobQueue.put(() -> methodB(message));
} catch (InterruptedException e) {
}
}
private void methodB(Message message) {
b.sendMethod(message);
}
}
class B {
public void sendMethod(Message message) {
// other logic
}
}
And my test would potentially look something like:
class Atest {
private A testSubject;
#Mock
private B b;
#Test
public void testASendsMessage() {
Message message = new Message("HELLO WORLD");
testSubject.methodA(message);
verify(b, timeout(100)).sendMethod(message);
}
#Before
public void setup() throws Exception {
testSubject = new A();
}
}
In general you want to avoid needing to verifying bits with multiple threads in a unit test, save tests with multiple running threads mainly for integration tests but where it is necessary look at Mockito.timeout(), see example above for how to use. Hopefully this helps?
I am looking for a way to catch all exceptions thrown by JUnit tests then re-throw them; to add more detail to the error message about the test state when the exception occurred.
JUnit catches errors thrown in org.junit.runners.ParentRunner
protected final void runLeaf(Statement statement, Description description,
RunNotifier notifier) {
EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
eachNotifier.fireTestStarted();
try {
statement.evaluate();
} catch (AssumptionViolatedException e) {
eachNotifier.addFailedAssumption(e);
} catch (Throwable e) {
eachNotifier.addFailure(e);
} finally {
eachNotifier.fireTestFinished();
}
}
This method is unfortunately is final so it cannot be overridden. Also as exceptions are being caught something like Thread.UncaughtExceptionHandler will not help. The only other solution I can think of is try/catch block around each test but that solution is not very maintainable. Could anyone point me to a better solution?
You could create a TestRule for this.
public class BetterException implements TestRule {
public Statement apply(final Statement base, Description description) {
return new Statement() {
public void evaluate() {
try {
base.evaluate();
} catch(Throwable t) {
throw new YourException("more info", t);
}
}
};
}
}
public class YourTest {
#Rule
public final TestRule betterException = new BetterException();
#Test
public void test() {
throw new RuntimeException();
}
}
Say I have a constructor where it's initialization can potentially throw an exception due to reasons beyond my control.
FantasticApiController(IAwesomeGenerator awesome,
IBusinessRepository repository, IIceCreamFactory factory)
{
Awesome = awesome;
Repository = repository;
IceCream = factory.MakeIceCream();
DoSomeInitialization(); // this can throw an exception
}
Ordinarily, when a Controller action in WebAPI throws an exception I can handle it via a csutom ExceptionFilterAttribute:
public class CustomErrorHandler
{
public override void OnException(HttpActionExecutedContext context)
{
// Critical error, this is real bad.
if (context.Exception is BubonicPlagueException)
{
Log.Error(context.Exception, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
}
// No big deal, just show something user friendly
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent("Hey something bad happened. " +
"Not closing the ports though"),
StatusCode = HttpStatusCode.InternalServerError;
});
}
So if I have a have a BoardPlane API method which throws a BubonicPlagueException, then my CustomerErrorHandler will shut down the ports to Madagascar and log it as an error as expected. In other instances when it's not really serious, I just display some user friendly message and return a 500 InternalServerError.
But in those cases where DoSomeInitialization throws an exception, this does absolutely nothing. How can I handle exceptions in WebAPI controller constructors?
The WebApi Controllers are created, and thus constructors called via HttpControllerActivators. The default activator is System.Web.Http.Dispatcher.DefaultHttpControllerActivator.
Very rough examples for options 1 & 2 on github here https://github.com/markyjones/StackOverflow/tree/master/ControllerExceptionHandling/src
Option 1 which works quite nicely involves the use of a DI container (you may well be using one already). I have used Ninject for my example and have used "Interceptors" Read More to intercept and try/catch calls to the Create method on the DefaultHttpControllerActivator. I know of at least AutoFac and Ninject that can do something simlar to to the following:
Create the interceptor
I don't know what the lifetime scope of your Madagascar and Log items are but they could well be injected into your Interceptor
public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
{
private ILog _log;
private IMadagascar _madagascar;
public ControllerCreationInterceptor(ILog log, IMadagascar madagascar)
{
_log = log;
_madagascar = madagascar;
}
But keeping to the example in your question where Log and Madagascar are some kind of Static global
public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
{
public void Intercept(Ninject.Extensions.Interception.IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch(InvalidOperationException e)
{
if (e.InnerException is BubonicPlagueException)
{
Log.Error(e.InnerException, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
}
}
FINALLY Register the interceptor In global asax or App_Start (NinjectWebCommon)
kernel.Bind<System.Web.Http.Dispatcher.IHttpControllerActivator>()
.To<System.Web.Http.Dispatcher.DefaultHttpControllerActivator>().Intercept().With<ControllerCreationInterceptor>();
Option 2 is to implement your own Controller Activator implementing the IHttpControllerActivator interface and handle the error in creation of the Controller in the Create method. You could use the decorator pattern to wrap the DefaultHttpControllerActivator:
public class YourCustomControllerActivator : IHttpControllerActivator
{
private readonly IHttpControllerActivator _default = new DefaultHttpControllerActivator();
public YourCustomControllerActivator()
{
}
public System.Web.Http.Controllers.IHttpController Create(System.Net.Http.HttpRequestMessage request, System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
try
{
return _default.Create(request, controllerDescriptor, controllerType);
}
catch (InvalidOperationException e)
{
if (e.InnerException is BubonicPlagueException)
{
Log.Error(e.InnerException, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
//DO SOMETHING WITH THE ORIGIONAL ERROR!
return null;
}
}
}
Once you have your own custom activator the default activator can be switched out in the global asax :
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new YourCustomControllerActivator());
Option 3 Of course if your initialisation in the constructor doesn't need access to the actual Controllers methods, properties etc... i.e. assuming it could be removed from the constructor... then it would be far easier to just move the initialisation to a filter e.g.
public class MadagascarFilter : AbstractActionFilter
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try{
DoSomeInitialization(); // this can throw an exception
}
catch(BubonicPlagueException e){
Log.Error(e, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ERROR
}
base.OnActionExecuting(actionContext);
}
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
public override bool AllowMultiple
{
get { return false; }
}
}