assertThat vs assertEquals for big String comparison - junit4

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.

Related

Expect an exception in Scala tests (no JUnit)

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.

Why am I getting an (inconsistent) compiler error when using a for comprehension with a result of Try[Unit]?

A common pattern I have in my code base is to define methods with Try[Unit] to indicate the method is doing something (like writing a transaction long to a SaaS REST endpoint) where there is no interesting return result and I want to capture any and emit any errors encountered to stdout. I have read on another StackOverflow thread this is entirely acceptable (also see 2nd comment on the question).
I am specifically and explicitly avoiding actually throwing and catching an exception which is an extraordinarily expensive activity on most JVM implementations. This means any answer which uses the Try() idiom won't help resolve my issue.
I have the following code (vastly simplified from my real life scenario):
def someMethod(transactionToLog: String): Try[Unit] = {
val result =
for {
_ <- callToSomeMethodReturningATryInstance
} yield Unit
result match {
case Success(_)
//Unit
case Failure(e) ->
println(s"oopsie - ${e.getMessage}")
}
result
}
Sometimes this code compiles just fine. Sometimes it doesn't. When it doesn't, it gives me the following compilation error:
Error:(row, col) type mismatch;
found : scala.util.Try[Unit.type]
required: scala.util.Try[Unit]
result
^
Sometimes the IntelliJ syntax highlighter shows the code as fine. Other times it shows an error (roughly the same as the one above). And sometimes I get the compiler error but not a highligher error. And other times it compiles fine and I get only a highlighter error. And thus far, I am having a difficult time finding a perfect "example" to capture the compiler error.
I attempted to "cure" the issue by adding .asInstanceOf[Unit] to the result of the for comprehension. That got it past the compiler. However, now I am getting a runtime exception of java.lang.ClassCastException: scala.Unit$ cannot be cast to scala.runtime.BoxedUnit. Naturally, this is infinitely worse than the original compilation error.
So, two questions:
Assuming Try[Unit] isn't valid, what is the Scala idiomatic (or even just preferred) way to specify a Try which returns no useful Success result?
Assuming Try[Unit] is valid, how do I get past the compilation error (described above)?
SIDENOTE:
I must have hit this problem a year ago and didn't remember the details. I created the solution below which I have all over my code bases. However, recently I started using Future[Unit] in a number of places. And when I first tried Try[Unit], it appeared to work. However, the number of times it is now causing both compilation and IDE highlighting issues has grown quite a bit. So, I want to make a final decision about how to proceed which is consistent with whatever exists (or is even emerging) and is Scala idiomatic.
package org.scalaolio.util
/** This package object serves to ease Scala interactions with mutating
* methods.
*/
package object Try_ {
/** Placeholder type for when a mutator method does not intend to
* return anything with a Success, but needs to be able to return a
* Failure with an unthrown Exception.
*/
sealed case class CompletedNoException private[Try_] ()
/** Placeholder instance for when a mutator method needs to indicate
* success via Success(completedNoExceptionSingleton)
*/
val completedNoExceptionSingleton = new CompletedNoException()
}
Replace yield Unit with yield ().
Unit is a type - () is a value (and the only possible value) of type Unit.
That is why for { _ <- expr } yield Unit results in a Try[Unit.type], just as yield String would result in a Try[String.type].

Groovy referencing variable without declaration

Why doesn't eclipse show an error when I use a variable without declaring it?
Edit:
AFAIK dynamic nature only means that type of variable is not known until run time. The variables must still be defined (explicitly or implicitly) before being used. For example - Python which is also a dynamic language reports this as an error.
Edit2:
How does groovy interpret this code so that it still isn't an error?
Because in dynamic languages like groovy, one could have implemented methodMissing() / propertyMissing(). So although such variable or method does not actually exist, it may be still not be an errors until the program is actually run. Such errors can usually only be detected at runtime and hence IDE's usually don't complain about it.
Although to hint you, eclipse is underlining such variables there which it is not able to statically reference.
EDIT :
To explain the concept by code example, just check the method test below. Now IDE can't know that something , that ... can actually be a method in this class.
This vastly helps in building DSLs in groovy.
class TestClass {
def test() {
def a = something.that.didnt.exist()
or how about some random statements that make no sense at all
a = ew Parser().doSomething() ew blah blah blah
}
def propertyMissing(String name) { println "$name"; return this }
def methodMissing(String name, args) { println "$name with $args"; return this }
}
new TestClass().test()
I think you may try to use #CompileStatic tag on method.
Then Eclipse will compile and check errors at compile time or in develop time.
I haven't Eclipse to check this now, so this is just for a proposal.

Does Scala io.Source.FromFile return any kind of exception?

I was reviewing my code for the last time searching for exceptions when I stopped on this line of code:
var list: Array[String] = Source.fromFile(this.Path).getLines.toArray
I searched in the documentation on scala-lang but it seems that none of the methods of that line throws any kind of ioException...
How is that possible?
EDIT:
try {
var list: Array[String] = Source.fromFile("").getLines.toArray
}
catch {
case ex:Exception => println(ex.getMessage)
}
does not print anything, why?
Checked exceptions are enforced by the javac, the JVM don't really know about them. And contrary to Java, Scala doesn't care about checked exceptions.
Look at Source for instance, you won't notice any code dealing with exceptions. Something that is impossible in good old Java, which would require try/catchs or throws clauses.
Despite that, a Scala library author may still want to make sure that Java users check for these exceptions, so there is the #throws annotation, which let you declare that a method may throw a exception just like throws Java clause. Make sure to keep in mind that #throws is only for Java consumption.
You may also want to take look at scala.util.control.Exception. It contains all sorts of goodies for dealing with exceptions.
Source.fromFile calls java.io.FileInputStream.open, which throws a FileNotFoundException if you give it a nonexistent file.
Source.fromFile doesn't catch this, so it will be seen in your code.
I suspect many of the other exceptions possible in the java.io package are similarly unhandled, but apparently undocumented.

how do you specify that an NUnit test should fail?

Is there a way to specify that you want an NUnit test to fail, meaning that a fail should be reported as a pass and a pass should be reported as a fail? This would be useful when testing your own NUnit extensions. Here is an example of something I would like to be able to do:
[Test]
[ExpectFail]
public void TypeOf_fail() {
string str = "abc";
str.Should().Be.TypeOf<int>();
}
This does not compile because [ExpectFail] is an imaginary attribute to illustrate what I want to do, but the code inside the method works fine. This problem is specific to testing an NUnit extension in that you can normally just easily write your tests to pass, not fail. In this case you need prove that it is possible to write a failing test using the NUnit extension that you are testing.
I know this is an old post, but here is what has helped me, using NUnit:
[TestCase("SomeValidValue")]
[TestCase("{3X5XFX9X-7XCX-4XCX-8X3X-3XAXEX9X0XBX}", ExpectedException = typeof(AssertionException))]
public void GetSpecificConfiguration(string key)
{
Assert.IsNotNull(Config.Instance.GetRecord(key));
}
This approach allows me to have the same test, with two expectations, one succeeding, and one failing.
Unit tests should be designed so that:
They set up some state
They run the method under test
They assert that one thing is correct after the method under test has completed
(reference: The Art of Unit Testing by Roy Osherove)
Why are tests that are designed to fail a bad thing? They could fail in unexpected ways, and still be marked as a pass because they failed. In your example, assuming that Should() is the method under test (though this point remains even if it isn't), you write the test above and mark it as 'expected to fail'. It fails. Everything is fine. In a couple of months you come back to Should() and realise it needs some refactoring, so you change its implementation.
Now, in your example, Should() throws an exception, because you've accidentally introduced a bug. But your test (which fails because of the exception now, not the logic) is marked as should fail, and it does, so it's still marked as a pass, despite the breaking change.
The test should be designed to pass, not to fail, that way if it fails in another, unexpected, way you'll be notified. So in your example you should write tests with opposite logic:
[Test]
public void TypeOf_ShouldBeString() {
string str = "abc";
str.Should().Be.TypeOf<string>();
}
or:
[Test]
public void TypeOf_ShouldNotBeInt() {
string str = "abc";
str.Should().Not.Be.TypeOf<int>();
}
(Not sure of the syntax you're using, so .Not probably will need replacing with the correct syntax, but the sentiment holds).
Edit2: If what you're trying to do is ensure that your Should() method fails (by failing an Assert. method) then what you want to do is catch the NUnit AssertionException which the Assert. static methods throw. Try this:
[Test]
[ExpectedException(typeof(AssertionException))]
public void ShouldBeTypeOf_WithInt_Fails() {
string str = "abc";
str.Should().Be.TypeOf<int>();
}
What about Assert.Throws<XXXException>(x.DoSomething());
The nice thing here is that if the test passes (i.e. the exception was thrown), the return value is the actual exception itself, and you can then interrogate it and Assert further based on that..
Given that in this case you're wanting to test NUnit extensions, which, I'm assuming, function by making Assert calls, you could Assert.Throws<AssertionException>(...), and then do the above.
I'm thinking of writing some similar test plumbing code which I might in turn need tests for, so I'll let you know if I discover anything else in this area.
If you mean that the block of code is expected to throw an exception for test to pass, here's the code:
[Test]
[ExpectedException(typeof(Exception))]
public void TypeOf_fail() {
string str = "abc";
str.Should().Be.TypeOf<int>();
}
Of course, replace Exception with the most specific exception possible.