How to test Exception being thrown with midje - unit-testing

Simple question. I'm trying to test in midje if my method triggers an exception. I could only find something like the following in the midje documentation.
(fact "Should throw a RuntimeException"
(my-method! anything) =throws=> (RuntimeException.)
Thanks.

Never mind. I found it.
(fact "Should throw a RuntimeException"
(my-method! anything) => (throws RuntimeException)
That works for me.

Related

WrongTypeOfReturnValue exception when using Mockito

I have faced an error related to the usage of Java 8 streams in a combination with Mockito. It turns out that this line causes a WrongTypeOfReturnValue exception while a test is run. But the weird part is that Idea is able to evaluate this fragment during debugging.
when(clientConfig_.getStringForEnums()).thenReturn(enumsList.stream().map(Enum::toString)
.collect(Collectors.toList()));
After investigation I've found out that that the original reason is related to the usage of Streams with thenReturn() method. After below refactor the test run successfully.
List<String> strForEnums= listWithEnums.stream()
.map(Enum::toString)
.collect(Collectors.toList());
when(clientConfig_.getStringForEnums()).thenReturn(strForEnums);

combining test.check and clojure test

I am having trouble to use test.check together with normal tests. I tried the whole day to figure out what is going on, but I am still not sure.
This is what I have now:
(deftest user-can-only-be-inserted-once
(;normal test))
(defspec insert-one-user-should-let-me-retrieve-that-one-user
gen-quantity
(prop/for-all ; test.check test))
Now, as long as I execute "lein test" from the console after each change in the test file it works as expected. However, running tests from the cursive repl or with the quickie plugin via "lein quickie" the repl will reload the namespaces not correct.
The effect is that, whenever a test fails and I fix that test it will still fail in the repl, so it looks like something is not working correctly there.
If anyone has an idea how to fix this, I'd be happy to hear it. I would also like to hear if someone has a different setup which combines normal tests and test.check or if this is not intended to work at all.
Thanks,
Sven
Update Actually I found out that the problem is not the combination of normal and test.check but the fact that I am trying to check an assertion is throw on a specific case. In normal test you would do this with (is (thrown? Assertion (function... But when I try this in test.check it just fails.
If I understand your update correctly, your test expects that the exception is thrown. If the exception does not occur, then the test should fail.
If so, then you will need to write the property in defspec to catch the exception, return it as a value, and verify that the exception occurs.
You could do something like this:
(defn catcher [f]
(try (f)
(catch Throwable t t)))
(defspec some-specification-name
(prop/for-all [...generator-bindings...]
(not-nil? (catcher (my-function generated-values)))))

Clojure not recognizing parent classes

I'm writing using wsimport to generate a client for a web service, however, when I try to initiate the binding with an Addressing feature, I get the following error:
Exception in thread "main" java.lang.ClassCastException: javax.xml.ws.soap.AddressingFeature cannot be cast to [Ljavax.xml.ws.WebServiceFeature;
I know for a fact that javax.xml.ws.soap.AddressingFeature extends javax.xml.ws.WebServiceFeature, so I'm not sure what's happening. I know you cannot downcast in Clojure, but casting to a parent should work.
From my understanding, objects should be autocast, and if they are not, clojure.core/cast should work, however, both throw an exception.
My code looks something like this:
(-> (com.test.TestAPISOAP.)
(.getTestWSHttpBinding
(javax.xml.ws.soap.AddressingFeature. true true)))
It looks like .getTestWSHttpBinding accepts an array (the [L in [Ljavax.xml.ws.WebServiceFeature), not a single element.
Try creating an array with AddressingFeature as a single element using clojure.core/to-array:
(-> (com.test.TestAPISOAP.)
(.getTestWSHttpBinding
(to-array [(javax.xml.ws.soap.AddressingFeature. true true)])))

Prevent System/exit in code I don't have access to

I'm playing with someone else's code by examining it in the repl.
It keeps calling System/exit, which brings down my repl. This is infuriating.
In all the code I have access to, I've mocked the calls out.
But it's also calling some library code I don't have the source to, both java and clojure, and this occasionally causes exits too.
Is there any way to catch these calls globally, so that an attempt to call them doesn't kill the repl thread? Ideally it would just throw an exception instead.
I think in java I could install a new SecurityManager to get this effect, but I've never done it
there seems to be something in that line here:
http://jroller.com/ethdsy/entry/disabling_system_exit
So I'm thinking something like:
(System/setSecurityManager (SecurityManager.))
only I somehow need to attach
public void checkPermission( Permission permission ) {
if( "exitVM".equals( permission.getName() ) ) {
throw new ExitTrappedException() ;
}
}
My best shot so far is:
(System/setSecurityManager
(proxy [SecurityManager] []
(checkPermission [p]
(when (= "exitVM" (.getName p))
(throw (Exception. "exit"))))))
or maybe
(System/setSecurityManager
(proxy [SecurityManager] []
(checkExit [n] false)))
But they both just destroy the repl
Or is there a better way of doing this?
Use AspectJ and intercept all Calls to System.exit() with a no op.
But you are right, just configuring the security manager would be saner.
You can also use clj-sandbox to restrict code you don't trust.
This one works for me in both, Clojures simple REPL, and in the Lein REPL, too
(def SM (proxy [SecurityManager] []
(checkPermission
[^java.security.Permission p]
(when (.startsWith (.getName p) "exitVM")
(throw (SecurityException. "exit"))))))
(System/setSecurityManager SM)
Ah. Even in the Cider REPL in Emacs.
The name is actually "exitVM.n", where n is the numeric exit code passed to System/exit
I still have an issue to extend this security manager. Surprisingly many Clojure functions call the security manager, and thus, when used inside of it, give an infinite loop, aka StackOverflowException.
(For the latter I opened anothe question: Security Manager in Clojure )
You can try this: http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

Exception handling for Unit Tests in c++

I'm trying to test a c++ code on an Nunit framework but I keep getting the following Exception
System.Runtime.InteropServices.SEHException : External Component has thrown an exception.
which is supposedly perfectly normal (I assume) anyway I wanna ignore it. (i.e. Use ExpectedException) This is my .h file
[Test, Description("Tests if an Entity has been successfully Locked")]
void test_LockOperation();
and the .cpp file
void TestDmObstacles::test_LockOperation()
{
lockVal = DbtoDmObstaclesAdapter::lock( CmnGuid::parseString( L"3B6DB8F8-4BA7-DD11-B6A7-001E8CDE165C" ) );
//When lock is successful the lockVal is 0
Assert::AreEqual(0, lockVal);
}
I wanna use ExpectedException but I don't know how to do it in c++. I tried the try/catch method as well but it didn't work (I just put the Assertion in the catch block)
PS: I can't use another framework it has to be Nunit
EDIT
Here is the try/catch approach I used
void TestDmObstacles::test_LockOperation()
{
try
{
lockVal = DbtoDmObstaclesAdapter::lock( CmnGuid::parseString( L"3B6DB8F8-4BA7-DD11-B6A7-001E8CDE165C" ) );
}
catch (...)
{
//Assert::Fail();
Assert::AreEqual(0, lockVal);
}
}
Is the exception expected, or is the exception acceptable?
If it is expected, then your unit test framework should have some kind of API that allows you to state the expected exception, and to fail the test if it does not occur. A quick trawl through the documentation yields the incantation:
[ExpectedException( "System.ArgumentException" )]
(replace System.ArgumentException with the exception you're expecting.)
If the exception is merely acceptable, then I would say that either your code or your test is broken. A unit test is to test that expected things happen. If there is a result in your test that only may yield a particular result, then you are not testing a consistent view of the unit from test to test. Hence, you're not really testing it.
It might indicate, for example, that your code is leaking an unexpected exception that it should be handling instead.
Your code sample doesn't match what you are trying to achieve : if the exception is expected, than catching it is not supposed to fail the test.
Note that I wouldn't recommend (at all) for the test to catch (...) : any thrown exception will induce the same test result, which I doubt is what you want.