I am trying to understand throws clause in JAVA , I wrote the following
piece of code:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
demo();
}
}
I understand that it won't compile as the exception has to be handled
in the main method and demo() should be defined with specifying a throws
clause for IllegalAccessException.
But when I change the exception to NullPointerException, the same
program compiles and executes:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new NullPointerException("Demo");
}
public static void main(String args[])
{
demo();
}
}
Related
For Example:
Class A{
string s = null;
public void method(){
s="Sample String";
}
}
I have a void method with similar scenario. How can I test such void method?
With void methods you should test the interaction with its dependent objects within the void method. I think a void method with no argument is rarely useful to test (but if you have a valid use case, please add it to your question). I provided you a simple example for a method with an argument but void as a return type:
public class A {
private DatabaseService db;
private PaymentService payment;
// constructor
public void doFoo() {
if(n < 2) {
db.updateDatabase();
} else {
payment.payBill();
}
}
}
And the unit test for this can look like the following
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
DatabaseService db;
#Mock
PaymentService payment;
#Test
public void testDoFooWithNGreaterTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(3);
verify(payment).payBill(); // verify that payment was called
}
#Test
public void testDoFooWithNLessThanTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(1);
verify(db).updateDatabase(); // verify that db was called
}
}
I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}
This is the easiest example of a complex issue. I haven't found the example of this problem anywhere in the entire internet. I'm validating the input in a validationMethod that return Boolean. Now, I need to use this method in calling class (run the flow if return is true, catch exception if return is false).
public class StringUtil{
public static boolean validateNumInput(String UserInput)
{
if(UserInput.matches("[0-9]+")){
return true;
} return false;
}
}
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
}
}catch(Exception e){
System.out.println("Big problem");
}
}
}
According to the documentation, you can filter catch clauses with a Boolean predicate. So, your validation method would need to throw an exception which you could filter for in your catch clause. But if you're doing that, you might as well roll your own custom exception and not have to deal with the Boolean at all. The other alternative is, in your calling code, treat the return code as a return code and throw your own exception.
Option 1:
public class StringUtil{
public static boolean validateNumInput(String UserInput)
{
if(UserInput.matches("[0-9]+")){
return true;
}
throw new Exception ("Validation failed!");
}
}
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
}
}catch(Exception e) when (e.Message == "Validation failed!") {
System.out.println("Big problem");
}
}
}
Option 2:
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
} else {
throw new Exception ();
}
}catch(Exception e) {
System.out.println("Big problem");
}
}
}
I have created a CustomException with a custom message and an error code.
public class CustomException extends RuntimeException{
private int errorCode;
public CustomException(String message,int errorCode){
super(message);
this.errorCode=errorCode;
}
public int getErrorCode(){
return this.errorCode;
}
public String getMessage(){
return "Message: "+super.getMessage()+" ErrorCode: "+this.errorCode;
}
}
When I add a null value in a list throw CustomException with the message "Null" and error Code 1. When I add an empty value the message for exception is "Empty" and error Code 2.
How I can capture and test error code in unit test?
I have done something like that:
public class MyListTester{
private Class exceptionType = CustomException.class;
#Test
public void testAddNonNullValue() {
exception.expect(exceptionType);
exception.expectMessage("Null");
list.add(null);
}
but I don't have acces to the error code
The trick is to use the expect method of the ExpectedException rule which takes a Matcher as parameter and to write a custom matcher for verifying the error code. Here is a complete example:
public class MyListTester {
#Rule
public ExpectedException exception = ExpectedException.none();
#Test
public void testAddNullValue() {
MyList list = new MyList();
exception.expect(CustomException.class);
exception.expectMessage("Null");
exception.expect(errorCode(1));
list.add(null);
}
#Test
public void testAddEmptyValue() {
MyList list = new MyList();
exception.expect(CustomException.class);
exception.expectMessage("Empty");
exception.expect(errorCode(2));
list.add(emptyValue);
}
private Matcher<? extends CustomException> errorCode(final int errorCode) {
return new CustomTypeSafeMatcher<CustomException>("errorCode " + errorCode) {
#Override
protected boolean matchesSafely(CustomException e) {
return e.getErrorCode() == errorCode;
}
};
}
}
Hi I have custom junit runner
public class InterceptorRunner extends BlockJUnit4ClassRunner {
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface InterceptorClasses {
public Class<?>[] value();
}
public InterceptorRunner(Class<?> klass) throws InitializationError {
super(klass);
}
#Override
public Statement methodInvoker(FrameworkMethod method, Object test) {
InterceptorStatement statement = new InterceptorStatement(super.methodInvoker(method, test));
InterceptorClasses annotation = test.getClass().getAnnotation(InterceptorClasses.class);
Class<?>[] klasez = annotation.value();
try {
for (Class<?> klaz : klasez) {
statement.addInterceptor((Interceptor) klaz.newInstance());
}
} catch (IllegalAccessException ilex) {
ilex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return statement;
}
#Override
public void run(RunNotifier notifier) {
FailListener listener = new FailListener();
notifier.addListener(listener);
super.run(notifier);
notifier.removeListener(listener);
}
}
and custom listener
public class FailListener extends RunListener {
#Override
public void testFailure(Failure failure) throws Exception {
System.out.println("test fails");
super.testFailure(failure);
}
public void testStarted(Description description) throws Exception {
System.out.println("Test started");
super.testStarted(description);
}
}
How can I log not only System.out.println("test fails"); but also Exception and some other information?
It seems to me that it possible to use failure, but I don't know how to.
The Failure object has a method getException().