Expect an exception in Scala tests (no JUnit) - scala

I had tests that should give null:
Object.someFunction(argUsedToGiveNull) should === (null)
But I've modified the function, and now I want the test to expect/assert the function given that value throws an IllegalArgumentException.
I'd like to do something like:
Object.someFunction(argNowThrowsException) should throw IllegalArgumentException
and note I am not using #Test JUnit structure.
Thanks!

an[IllegalArgumentException] should be thrown by Object.someFunction(argNowThrowsException)

To test for an expected exception:
an [ExceptionType] should be thrownBy {
Object.someFunction(argThrowsException) }
Note that the evaluatingkeyword used to be used for this but is now deprecated.

Related

Mocking a Source in Akka Streams

I have a wrapper class AwsS3Bucket which when invoked, returns a source Source[ByteString, NotUsed]. In my unit test case, I have mocked this client and do the necessary assertions.
val source = Source.fromIterator(() => List(ByteString("some string")).toIterator)
when(awsS3Bucket.getSource(any[String])).thenReturn(source)
However, now I want to test the error scenario wherein I want the getSource method to throw an exception.
I tried the following code,
val error = new RuntimeException("error in source")
when(awsS3Bucket.getSource(any[String])).thenReturn(error)
but it gives me a compilation issue saying that
Cannot resolve overloaded method thenReturn
Can anyone please let me know the correct method of returning an exception in a Source in akka streams.
You have to use thenThrow(new RuntimeException("error in source")) to stub an Exception.
That said, you may find issues sometimes with checked exceptions as Scala treats all exceptions as runtime, so they aren't declared in the signature, and standard Mockito will validate you're stubbing an exception that can be thrown by the stubbed method.
In mockito-scala that check has been removed to acknowledge the fact that all exceptions behave as runtime in Scala

Scala Future.failed throws the exception passed to it

I'm using the constructor Future.failed to create a failed future, but the failed future still throws the exception when I think it should not.
The method session.loadAll does throw an exception.
I'm also using the Play Framework
It even happens using a try-catch block
I think that Future.failed is not throwing the exception. It looks like it is, because the stack trace is generated at the place where the exception is created.
So, if you use a method like Await.result, or another method that assumes that a future is successful, you will see the exception re-thrown, but the stack trace will make it look as if it was thrown in Future.failed.
First, I'm not quite sure why you're using a future here because these don't look like asynchronous calls.
To answer your question, however, I'm not entirely sure what is going on here, but it looks like you need to be handling the exception. The consumer of the future should use either Future.onComplete and pattern match a Failure type, or Future.onFailure and pattern match on Throwable types.
Scala docs on Future: http://docs.scala-lang.org/overviews/core/futures.html

How to test for two or more exceptions in ScalaTest?

I am using ScalaTest for unit testing. I currently have the following:
f(x) should produce[Exception]
I would like to specify two or more subclasses of Exception, e.g.
f(x) should (produce[ExceptionA] or produce[ExceptionB])
Is this possible? If not, what is the recommended way to proceed?
I would look at restructuring either your code or your tests if you've got a block of code that is non-deterministic in the exception that it will throw. That said, you could use an evaluating block to capture the thrown exception and then check if it's one of the required types. e.g.
val caught = evaluating {
// code that should throw an exception
} should produce [Exception]
then
assert(caught.isInstanceOf[ExceptionA] || caught.isInstanceOf[ExceptionB])

assertThat vs assertEquals for big String comparison

Everyone says that we should use the new assertThat from Junit, but, for big Strings comparison it's seems to be some lack of feature.
Example:
#Test
public void testAssertThat() throws Exception {
Assert.assertThat("auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei",
CoreMatchers.equalTo( "auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" ) );
}
#Test
public void testAssertEquals() throws Exception {
Assert.assertEquals( "auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei",
"auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" );
}
assertEquals prints an easier to read error message:
org.junit.ComparisonFailure:
expected:<...uihaeuieahuiaehuieah[u]aiehiaueheauihaeuiha...> but
was:<...uihaeuieahuiaehuieah[e]aiehiaueheauihaeuiha...>
while assertThat prints this:
java.lang.AssertionError: Expected:
"auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei"
but: was "auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei"
Is there a way to get the same behavior with assertThat?
The friendly message org.junit.ComparisonFailure: expected... comes from the fact that it is the way that JUnit works with assertEquals and with String as input.
In this way, Junit throws org.junit.ComparisonFailure if the String comparison fails.
In your IDE, the comparison is more readable indeed. For example, in Eclipse, you can double- click on the failed Junit test to display a string comparison.
Like this :
AssertThat has a different semantic and the javadoc says it explicitly :
Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value.
And as the name implies, AssertionError has a semantic wider.
To conclude : if you want keep the friendly message for String, you should go on using AssertEquals for String comparisons.

Nunit: Which assert to use to ensure that everything passed at the end of my unit test?

I have written a test and I just want to ensure that everything passed and no exceptions were thrown ?
Is there some kind of special Assert to use at the end of the test?
What are the recommendations here?
Thanks in advance
The unit test will fail if an exception is thrown anyway. That is of course unless you're expecting it to fail, in which case you can capture and assert it, something like:
var exception = Assert.Throws<Exception>(() => MethodThatShouldThrowAnError());
Assert.AreEqual("Not Brilliant", exception.Message);
If you use Fluent Assertions (which your tag suggests), you can do:
Action act = () => MethodThatShouldNotThrowAnError();
act.ShouldNotThrow();
Just don't write any return statements in the test. Then the fact that test is finished with no exception will exactly mean that everithing in the test is passed.