Having trouble calling a method in a different class with Java - java

Okay so I'm doing some practice with JUnit Test cases and I'm trying to call a method from a different class in Java, but I can't figure it out. The classes are in different SOURCE FOLDERS so not sure if that could be a reason?
Below is a small snippet of the code, with the constructors and an example of how I'm trying to call the method.
package common;
public class MathTest {
#Test
public void test1(){
if (mMultiply(5, 6)== 30){
System.out.println("mMultiply Test has passesd");
} else {
System.out.println("mMultiply Test has failed");
fail("Multiply failed for inputted parameters. ");
And now here's the the other class with the method I'm trying to call
package common;
public class math {
public static int mMultiply(int x, int y){
return x*y;
}

Since it's a static method, just import the class in your JUnit file test. Then use the Assert class of JUnit to test your function. In this case, use assertEquals.
So I would rewrite the test as :
#Test
public void test1(){
assertEquals(math.mMultiply(5, 6),30);
}

You need to tell your method which class the static method is in i.e.:
if (math.mMultiply(5, 6)== 30){
System.out.println("mMultiply Test has passesd");
}
Incidentally, all Java classes should start with a capital letter, and there's already a core Java class called Math, so you might want to find another name.

try math.mMultiply It is a static method so you must specify in which class it resides

When you call mMultiply(5,6), do it like this: math.mMultiply(5,6).

Since it's a static method, you call it with its class name before it:
math.mMultiply(value1, value2).
Also, check the java code writing manuals. Class names begin with capital letter, so I would change the class of the math class to Math.

Related

Helper class in Java Spring

I'm familiar with basic java but I'm very new to Spring. Previously I worked in php Laravel. I'm sorry if I sound dumb. I wanted to know if there's any way to declare and handle Helper methods in Spring framework like Laravel?
Edit:
public class Helper {
publin int help() {...}
}
What I wanted was to call help() without Helper object or class name (considering the help() method is static). I simply wanted to call help() from anywhere in the project like
public class X {
public void genericMethod() {
int i = help(); //If it is posssible
}
}
Any type of help is appreciated. Thanks in advance.
If you want to call a method without having an object, the method needs to be static.
public class Helper{
public static void help(){}
}
You can then call it from anywhere in the same project by adding an import to the Helper class and writing Helper.help(). Or, you can add a static import to Helper.help and just write help(). All of this is explained in the Java tutorial. It is not possible in Java to have global project-wide imports that can be called from anywhere.
I'm not sure I fully understand the question but I think you are talking about having custom Utility classes. To have a Helper class you can write it using public static methods.
public class Helper {
public static help() {
// insert helpful things here
}
}
That way you can access it from any class by calling Helper.help().

Accessing a class inside a non-existing class

How does this work?
EDIT: Being static is not a good explanation, because I can use non-static methods and it will all work. Updated the code to reflect that.
I have this in a file called Foo.java:
// This is in the Foo.java file
class Test {
public void printSomething() {
System.out.println("In Foo.Test");
}
};
and this in a file called Caller.java:
// This goes in the Caller.java file
public class Caller {
public static void main(String[] args) {
Test test = new Test();
test.printSomething();
}
}
I can execute my Caller and it will print In Foo.Test. How can this not be a compilation problem? I don't even have a Foo class created. I don't even have to define Foo.Test in the Caller.
This is on Eclipse Luna, Java8.
Java is weird like that. You could have a file without any lines of code and it would still compile. Go on try it.
Now, I think you are confusing Test with Foo.Test (I understand, it's Friday).
Intrinsically what you defined is this:
public class Foo {} // this is by default, but don't try to use it because you didn't define the scope
class Test {}
And your perplexity is "OMG, Test is the impure offspring of a non-existing class!!!", because you were expecting something like
public class Foo {
class Test {}
}
This has nothing to do with a method being static. It is about quirkiness in the javac.
Happy Friday everyone! Time for happy hour.
The main-Method of the Foo.java is declared static
calling static methods works without creating a object of the class.
E.g you can create following Method in Foo.java
class Test {
public static void test(String test) {
System.out.println(test);
}
};
Now you can call Test.test("No object will be created"); and there will be NO instance of Test
A java file could contain single public class, but it could have as much non-public classes (package-local in your case) as you wanted.
Foo.Test is for inner classes. The one you declared is top level type.

Java - Declare Class Once Use Anywhere

Very simple problem but im not understanding static correctly.
I have java file which holds my main and its call testMain.
With my testMain it makes many classes with use other classes.
E.g. testMain>>GUI and testMain>>model and testMain>>controller
Now i have a class called generatorTester which i would like to declare once like:
public static utils.generatorTester randomGen = new utils.generatorTester ();
(utils is my custom package for my common classes)
Why does the above line not aloud me to do the following
classNameOfMainFunction.randomGen
Im i programming wrong here? Is this even possbile.
I bassicly want to make the class globably and use it any where.
A public static field of a public class can be used anywhere, you just need to use the right syntax to access it.
If you declare:
package foo;
public class Global {
public static Some thing;
}
And do
import foo.Global;
you can access the field with
Global.thing
Alternatively, you can do
import static foo.Global.thing;
and access it with
thing
About the best you can get is this:
public abstract class GloballyUsed {
public static int method() { return 4;
/* determined by fair
* dice roll, guaranteed to be random */
}
and:
GloballyUsed.method();
to call elsewhere.
Note per comment (I just learned this) since Java 5 you can import just a specific method name as:
import static {package}.GloballyUsed.method;
Note I added the keyword abstract, this is to further convince you that you never actually instantiate GloballyUsed. It has no instances. You probably have some reading to do on what static means.

How to verify that a specific method was not called using Mockito?

How to verify that a method is not called on an object's dependency?
For example:
public interface Dependency {
void someMethod();
}
public class Foo {
public bar(final Dependency d) {
...
}
}
With the Foo test:
public class FooTest {
#Test
public void dependencyIsNotCalled() {
final Foo foo = new Foo(...);
final Dependency dependency = mock(Dependency.class);
foo.bar(dependency);
**// verify here that someMethod was not called??**
}
}
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there ยง4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.
Use the second argument on the Mockito.verify method, as in:
Mockito.verify(dependency, Mockito.times(0)).someMethod()
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):
import static org.mockito.Mockito.*;
There are actually many ways to achieve this, however it's (arguably) cleaner to use the
verify(yourMock, times(0)).someMethod();
method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:
verify(yourMock, times(5)).someMethod();
Alternatives are:
verify(yourMock, never()).someMethod();
Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:
verifyZeroInteractions(yourMock)
Please Note:
verifyZeroInteractions(Object... mocks) is Deprecated.
Since Version 3.0.1. The now recommended method is:
verifyNoInteractions(yourMock)
As a more general pattern to follow, I tend to use an #After block in the test:
#After
public void after() {
verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}
Then the test is free to verify only what should be called.
Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.
So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.
Both the verifyNoMoreInteractions() and verifyZeroInteractions() method internally have the same implementation as:
public static transient void verifyNoMoreInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
public static transient void verifyZeroInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.
Just as a suggestion, if you want to be more aligned at syntax level with Behavior-driven development style there is BDDMockito:
You could use:
then(dependency).should(never()).someMethod();
As an equivalent replacement of:
verify(dependency, never()).someMethod();

Calling method without object

I have built a small (and 3 methods only!) api for myself, and I want to be able to call it like how you would call a method in Powerbot (A Runescape botting tool (I use it, but for programming purposes, not for actual cheating purposes)), without creating an Object of the file you'd require. How would i be able to do this?
You will need to create static methods, so you will need to do something like so:
public class A
{
public static void foo()
{
...
}
}
And then, you can call them like so:
public class B
{
...
A.foo();
}
Note however that static methods need to be self contained.
EDIT: As recommended in one of the answers below, you can make it work like so:
package samples.examples
public class Test
{
public static void A()
{
...
}
}
And then do this:
import static sample.examples.Test.A;
public class Test2
{
...
A();
}
If you use the static keyword when importing your class, you can use its methods as if they belong to the class you're importing them to. See:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
And of course your "api methods" need to be static as well.
The best way i found out for me was to extend my activity (If i said it right)...
MAIN CLASS
public class myMainActivity extends myMiniApi{
...
}
I think this is a better way (my opinion) to do this, Just call your method like you normally would as if it were in the same class. example:
randomMethod();

Categories