hey guys i have this Junit test code for factorial
#org.junit.Test
public void testIterationAAA()
{
Iteration test = new Iteration("AAA");
int result = test.factorial("AAA");
assertEquals("exceptionMessage",result);
}
supposedly since a string's factorial cant be calculated the exception i made should be thrown but how to test it using Junit??
import org.junit.Assert;
...
#org.junit.Test
public void testIterationAAA()
{
try {
Iteration test = new Iteration("AAA");
int result = test.factorial("AAA");
// The above line is expected to throw an exception.
// If the code does not throw an exception, fail the test.
Assert.fail("An exception should have been thrown");
} catch (Exception ex) {
// Nothing to do. Exception was expected in this test case.
}
}
You should use expected attribute
#Test(expected=SomeException.class)
Related
When handling errors in my cmdlet development, I encounter an unexpected behavior of the ThrowTerminatingError method.
Calling the method results in an unhandled exception of PipelineStoppedException. Thus, I do not get a formatted error in PowerShell, but a long unhandled exception error message.
My code corresponds to the following structure:
protected override async void ProcessRecord()
{
try
{
var transferClient = new TransferClient(...);
var result = await transferClient.GetAsync(); // Throws an AuthenticationException
}
catch (AuthenticationException exception)
{
var record = new ErrorRecord(exception, "TestException", ErrorCategory.AuthenticationError, null);
ThrowTerminatingError(record); // Unhandled exception
}
}
System info:
Microsoft.PowerShell.SDK: 7.2.8
System.Management.Automation: 7.2.8
Target: PowerShell 7
I used ListeningExecutorService of guava in my project, got confused about the exception handling.
I used a thread pool, submit a task to it, and set a timeout to the listenableFuture, and add a callback to it.
final ListeningExecutorService threadPool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
Futures.addCallback(listenableFuture, new FutureCallback<**>() {
#Override
public void onSuccess(#Nullable ** data) {
xxxxxxx;
}
public void onFailure(Throwable t) {
xxxxxxxxxx;
if (t instanceof CancellationException) {
throw new QueryException("yyyy");
} else {
throw new QueryException("zzzzz");
}
}
});
I can't catch the exception inside the callback. So I use another ListenableFuture to get the exception
ListenableFuture allFutures = Futures.allAsList(allFuturesList);
try {
allFutures.get();
} catch (CancellationException ce) {
throw new QueryException("");
} catch (InterruptedException t) {
throw new QueryException("");
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof QueryException)
throw (QueryException) t;
else
throw new QueryException();
} catch (QueryException qe) {
throw qe;
} catch (Exception e) {
throw new QueryException();
} finally {
}
But I when the callback throw a QueryException, the allFutures can't catch it, allFutures can only catch a CancellationException without the detail error message.
How can I get my detail error message?
Futures.allAsList doesn't do what you expect it to do
From the Javadoc: (emphasis is from me)
Canceling this future will attempt to cancel all the component futures, and if any of the provided futures fails or is canceled, this one is, too.
What you should probably do is create your own aggregating future. You can base your code on Guava's own internal mechanism. See the source code for more info.
Anyways, do not throw exceptions in your FutureCallback::onFailure method.
I am unable to catch the STException thrown by the STGroupFile. This is a problem. I need to abort if the template is bad. To reproduce this problem, I have this incorrect template file called tmp.stg:
temp1(param1)::=<<
%if(param1)%
%param1:{%temp2(p)%}; separator"\n"%
%endif%
>>
And this groovy code to process it:
#!/usr/bin/env groovy
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
try {
group = new STGroupFile(fn.toString());
} catch (Throwable e) {
throw new Exception("Caught first exception");
}
try {
group.registerRenderer(Integer.class, new NumberRenderer());
} catch (Throwable e) {
throw new Exception("Caught second exception");
}
throw new Exception("You should not see this");
}
}
Gex.main()
When I run that script, I get an error message but I cannot catch the exception:
can't load group file file:tmp.stg
The error message comes from STGroupFile.java:
throw new STException("can't load group file "+fileName, e);
But I am unable to catch this exception. How can I catch this exception and abort?
Following the advice of The ANTLR Guy, I extended the STErrorListener to throw an exception instead of printing a message to stderr. It looks like this:
File: lib/GexListener.groovy
import org.stringtemplate.v4.STErrorListener;
import org.stringtemplate.v4.misc.STMessage;
import org.stringtemplate.v4.misc.ErrorType;
class GexListener implements STErrorListener {
#Override
public void compileTimeError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void runTimeError(STMessage msg) {
if ( msg.error != ErrorType.NO_SUCH_PROPERTY ) { // ignore these
throw new Exception(msg.toString());
}
}
#Override
public void IOError(STMessage msg) {
throw new Exception(msg.toString());
}
#Override
public void internalError(STMessage msg) {
throw new Exception(msg.toString());
}
public void error(String s) { error(s, null); }
public void error(String s, Throwable e) {
System.err.println(s);
if ( e!=null ) {
throw new Exception(msg.toString());
}
}
}
Then the master script bin/gex.groovy looks like this:
#!/bin/bash
//usr/bin/env groovy -cp ${0%/*}/../lib "$0" "$#"; exit $?
#Grab(group="org.antlr", module="ST4", version="4.0.8")
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.NumberRenderer;
import GexListener
public class Gex {
public static void main(String [] args) {
System.out.println("Processing...")
File fn = new File("tmp.stg")
STGroupFile group;
GexListener listener = new GexListener();
group = new STGroupFile(fn.toString());
group.setListener(listener);
group.registerRenderer(Integer.class, new NumberRenderer());
System.out.println("You should not see this line")
}
}
Gex.main()
When it executes, there is a nasty side effect where the stacktrace is printed twice, but the program aborts before printing the last sentence "You should not see this line", which is the desired behaviour.
As you pointed out in a separate email: "I discovered that the exception is actually caught and not re-thrown. This happens inside STGroup.java:"
catch (Exception e) {
errMgr.IOError(null, ErrorType.CANT_LOAD_GROUP_FILE, e, fileName);
}
Why not override the IOError function (or a function in the listener that it calls?) to just re-throw e?
I would like to test a method, in JUnit4, that does not pass at the first caught exception, but if all calls to the tested method throw exception. And I would like to know if this is possible.
I explain : let us say I have the method
public void setFromFen(String fenValue) throws IllegalArgumentException
in a class Position.
In PositionTest Junit4 class, I would like to do something like this :
#Test(expected=IllegalArgumentException.class){
...
setFromFen("2"); // throws IllegalArgumentException
setFromFen("8/8/8/8/8/8/8/8"); // does not throw IllegalArgumentException
...
}
so that the test only succeed if all calls to setFromFen fail.
In this case, though the second test does not throw IllegalArgumentException, the test succeed : and that's not what I want.
Is is it possible to get success only if all tests lines throws IllegalArgumentException ?
I think this is outside of the possibilities of the annotation.
You'll probably need something along these lines:
#Test
public void thatAllCallsFail() {
int failureCount = 0;
try {
setFromFen(this.sampleString1);
}
catch( final Exception e ) {
failureCount++;
}
try {
setFromFen(this.sampleString1);
}
catch( final Exception e ) {
failureCount++;
assertEquals("All 2 calls should have failed", failureCount, 2);
}
}
I'm not for a second suggesting that that is a nice way of doing it.
If you're looking for a more generic solution, perhaps adding your strings to a collection and looping over them...
#Test
public void thatAllCallsFail2() {
final String[] strings = new String[] { sampleString1, sampleString2 };
int failureCount = 0;
for (final String string : strings) {
try {
setFromFen(string);
}
catch( final Exception e ) {
failureCount++;
}
}
assertEquals("All " + strings.length + " calls should have failed", failureCount, strings.length);
}
Of course, neither of these solutions will tell you which call did not throw an exception if the tests were to fail.
I have this method that tries to get a list of things:
private static IQueryable<Thing> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select thing;
}
catch (Exception exception)
{
return new EnumerableQuery<Thing>(?????);
}
}
}
I want to return an empty IQueryable if I can't for whatever reason get the query to run. I don't want to return NULL because that could break the calling code. Is it possible or am I going totally wrong about this?
These answers are good and do work, however I have always felt using Empty and not creating a new List is cleaner:
Enumerable.Empty<Thing>().AsQueryable();
Try the following:
private static IQueryable<Thing> GetThings(int thingsType)
{
IQueryable<Thing> things = new List<Thing>().AsQueryable();
try
{
things = from thing in entities.thing.Include("thingStuff")
select thing;
return things;
}
catch (Exception exception)
{
return things;
}
}
I would add block finally {} and put my return type in that code.
This will take care of the issue by returning the type that your application expects.
private static IQueryable<T> GetThings(int thingsType)
{
IQueryable<T> list = new List<Thing>().AsQueryable();
try
{
list = from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// handle exception here;
}
finally {
return list;
}
}
}
Returning empty IQueryable<>
DbSet.Take(0)
I think this would be tidier:
private static IQueryable<T> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// Exception handling code goes here
return new List<Thing>().AsQueryable();
}
}