Ambiguos JAVA Interfaces - error-handling

How can you define the classes/interfaces Adult, Student and Engineer so that the next sequence to give compilation error only where specified?
class Test {
public static void main(String args[]) {
Adult a = new Student(); //without giving compilation error
Adult b = new Engineer();//without giving compilation error
a.explorare(); //without giving compilation error
b.explorare(); //without giving compilation error
a.afisare(); //without giving compilation error
b.afisare(); //compilation error

That's not possible, if a.afisare() compiles then so should b.afisare().

Related

bytebuddy official demo throw Exception "Class already loaded: class foo.Bar"

Section "Working with unloaded classes" in Official document give a demo, I run it on my machine then throw an exception Class already loaded: class foo.Bar。
class MyApplication {
public static void main(String[] args) {
TypePool typePool = TypePool.Default.ofSystemLoader();
new ByteBuddy()
.redefine(typePool.describe("foo.Bar").resolve(), // do not use 'Bar.class'
ClassFileLocator.ForClassLoader.ofSystemLoader())
.defineField("qux", String.class) // we learn more about defining fields later
.make()
.load(ClassLoader.getSystemClassLoader());
assertThat(Bar.class.getDeclaredField("qux"), notNullValue());
}
}
bytebuddy version is 1.10.22
The problem is in the last line Bar.class.getDeclaredField("qux") which loads the Bar class upon validation of the code. I fixed this in the example. Rather use the return value of load which returns Bar.

How can I throw an SQLServerException (or SQLException) with Mockito?

I am unable to create an instance of SQLServerException because the ctors are all internal. Getting below error when using SQLException
org.mockito.exceptions.base.MockitoException: Checked exception is
invalid for this method!
Method signature (on SQLServerPreparedStatement):
public boolean execute() throws SQLServerException, SQLTimeoutException
and... public final class SQLServerException extends SQLException
Mock:
val fakeCmd : SQLServerPreparedStatement = mock()
...
whenever(fakeCmd.execute()).thenThrow(SQLException()) // this line fails
What am I doing wrong? Shouldn't I be able to throw the base/super exception?
Re Suggested Question:
The suggested question is very different from what I'm asking, the op in the other question is trying to throw SomeException which is not thrown by List.get nor in the inheritance tree
If you see "Method signature (on SQLServerPreparedStatement)" above, the method throws SQLServerException => public final class SQLServerException extends SQLException
But it doesn't like whenever(fakeCmd.execute()).thenThrow(SQLException())
Further, the accepted answer as pointed out is to throw RuntimeException because IndexOutOfBoundsException extends RuntimeException
In this case, so is SQLServerException extends SQLException
I commented about another question and there is a answer (not the accepted one) in the end that may be suitable in your case.
A workaround is to use a willAnswer() method.
For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:
given(someObj.someMethod(stringArg1)).willAnswer(invocation -> {
throw new Exception("abc msg");
});
The equivalent for plain Mockito would to use the doAnswer method
Here is the direct link to that answer: https://stackoverflow.com/a/48261005/13210306

Why is it saying that my public class is not defined when I only have one public class and the class file

import java.util.Scanner;
public class Lab6_2{
public static void main(String[] args){
Scanner sc_1 = new Scanner(System.in);
int numnber, i;
System.out.println("Enter an integer between 1 and 10.");
number = sc_1.nextInt();
}
}
This code is saying "2 errors found:
File: C:\Users\danwr\Downloads\lab 6_2.java [line: 2]
Error: The public type Lab6_2 must be defined in its own file
File: C:\Users\danwr\Downloads\lab 6_2.java [line: 7]
Error: number cannot be resolved to a variable"
Based on your error message I see two issues. The first is it appears that your .java file is named "lab 6_2.java" (with a space character). It needs to be named "lab6_2.java". However, be careful with this - Windows doesn't care that you use "lab" vs. "Lab" but on Unix the file would have to be named "Lab6_2.java".
As for the second error - where is number defined? (and is it spelled correctly)?

junit.framework.AssertionFailedError: No tests found in register

I'm having a problem getting this test case to work. Can anyone point me in the right direction? I know I'm doing something wrong, I just don't know what.
import org.junit.*;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
#SuppressWarnings("deprecation")
public class register extends SeleneseTestCase {
Selenium selenium;
private SeleniumServer seleniumServer;
public static final String MAX_WAIT = "60000";
public final String CRN = "12761";
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setAvoidProxy(true);
rc.setSingleWindow(true);
rc.setReuseBrowserSessions(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://google.com/");
seleniumServer.start();
selenium.start();
}
#Test
public void register_test() throws Exception {
//TESTS IN HERE
}
#After
public void tearDown() throws Exception {
selenium.stop();
// Thread.sleep(500000);
}
}
And I'm getting the following errors:
junit.framework.AssertionFailedError: No tests found in register
at jumnit.framework.TestSuite$1.runTest(TestSuite.java:97)
I'm stumped.
You can't both extend TestCase (or SeleniumTestCase) and also use JUnit annotations (#Test). The test runners for JUnit3 and 4 are different, and my assumption is when JUnit sees that you've extended TestCase, it uses the old runner.
Remove the #Test annotation, and instead follow the old convention of naming your test with the word "test" prefixed, and that will fix it.
public void testRegister() throws Exception {
//TESTS IN HERE
}
PS. I'd recommend following more standard Java naming conventions, such as camel casing.
PPS. Here's a link that explains this in more detail.
This means you did not created method names starting with test in following test cases class what you running currently
I was able to solve this error in my case--that is, running tests with a <junit> Ant task--by pointing to a 1.7 or later version of Ant. Ant 1.7+ honors nested <classpath> elements, in which I was pointing to a JUnit 4.x jar, which as CodeSpelunker indicated understands #Test annotations. http://ant.apache.org/faq.html#delegating-classloader provided the aha moment for me.
I'm using mockk in Kotlin for Android and I had this error.
My class was declared like this (autogenerated by Android Studio):
class MyClassTest : TestCase() {
but removing TestCase fixed the error
class MyClassTest {

VB.Net why is this not a bug?

I encounter what I believe to be a bug and I was just wondering if this is already known as a issue or if this is not a issue and why.
The problem related to Read Only Properties on a Type when compiling with the VB.Net Compiler in Visual Studio 2008.
Follows are the class definitions and a small C# program which will not compile. (And is correct in not compiling IMHO because the property being set in the Delegate is Read-only)
public interface ITest
{
bool PrivateBool { get; }
}
public class TestClass : ITest
{
bool privateBool = false;
public bool PrivateBool
{
get
{
return privateBool;
}
}
bool publicBool = false;
public bool PublicBool
{
get { return publicBool; }
set { publicBool = value; }
}
}
class Program
{
static void Main(string[] args)
{
TestClass tc = new TestClass();
//Compile Error
//tc.PrivateBool = false;
//Compile Error
//Action act = new Action(delegate()
//{
// tc.PrivateBool = false;
//});
//Action<TestClass> test = new Action<TestClass>(delegate(TestClass tcc)
//{
// tcc.PrivateBool = false;
//});
//Compile Time Error
//Action<TestClass> test = new Action<TestClass>( tz=> tz.PrivateBool = false);
//Compile Time Error
//Action test = new Action(tc.PrivateBool = false);
}
}
In VB.Net However this is a larger issue… the program will compile and execute with no exception. But the property is not set.
This was a nightmare to catch in the debugger at Run time and we feel that the compiler should have caught that we are assigning to a ready only property just as the CSharp compiler alerts you when compiling.
Module Module1
Sub Main()
Dim tc As New TestClass()
Dim setP = New Action(Of TestClass)(Function(d As TestClass) _
d.PrivateBool = False _
)
setP.Invoke(tc)
End Sub
End Module
Can anyone explain if this is correct logic and why?
I assume that someone will respond that the job of the compiler was fulfilled by examining the parameter type to the delegate and that the delegate was typed to accept that parameter just as it should when parsing a Method Body or a Function Body.
My rebuttal to this would be that the compiler DOES throw an error when that property is attempted to be set from within a method but not the delegate. Delegates should be parsed the same as a Method.
Is the C# compiler over extending itself? I think not. My experience is that this is a bug in the vb.net compiler and should be fixed by a patch to the IDE.
Last but surely not least what occurs when the Invoke happens?
The delegate surely does not use reflection to set the property automagically so I assume the CLR sees the read-only qualifier and a NOOP gets executed. Is that actually what occurs or is the behavior undefined?
Thank you for your time!
In VB.NET 2008, there are no statement lambdas. All lambdas are functions. They return a value, not perform an action.
Your VB lambda simply compares d.PrivateBool and False and returns the result of the comparison.
This is not a bug and by design. It is therefore advisable to avoid assigning VB.NET 2008's lambdas to an Action, this is highly confusing for an unprepared person.
Statement lambdas appeared in VB.NET 2010.