JMockit : Inspect local variables of a method - java

Is it possible to inspect local variables of a method in JMockit?
Source
void foo(){
boolean isPresent = false;
/// ... something here sets isPresent
}
Test
can I check the value of isPresent at the end of call of foo() using JMockit?

Rather than trying to do some obscure mocking mechanism. Try refactoring the code to something that you can test:
void foo(){
boolean isPresent = isPresent();
}
boolean isPresent(){
....
}
Also, consider this. If the variable's value never escapes the method and does not cause some other effect (which should be testable), why try to test it? Or why is it even there? Testing that a method scope variable's value is x has no value. Testing that the method resulted in y because the variable was x has value.

Related

How do I use return statements from a method as a parameter to another method?

I'm using a class variable, which I assigned a value in a method return. When I'm trying to use the return value as a parameter for another method it gives an error unless I declare the return statements again, which means I'd be creating a new local variable I'm guessing, and not using the class variable. So is it possible to use the return value, instead of ending up declaring a new variable.
I'm just asking whether it's possible. If it is, then there's probably something else wrong with my code.
When you have method returnOne do this:
public int returnOne() {
return 1;
}
And you have another method isOne like this:
public boolean isOne(int number) {
return (number == 1)
}
You can use the result of returnOne in isOne as a parameter like this:
boolean result = isOne(returnOne());
Hope this helps!

jmockit issue when mocked class contains method returning Integer

JMockit is not returning the Integer set as the return value in an expectation.
public interface Foo {
Integer getInt();
}
#Test
public void test(#Mocked final Foo foo) {
final Integer anyInt = 3;
new Expectations() {{
foo.getInt(); result = anyInt;
}};
assertThat(foo.getInt(), equalTo(anyInt));
}
fails with message:
java.lang.AssertionError:
Expected: <3>
but: was <0>
Any idea why?
JMockit 1.14
Thanks
The JMockit Expectations API has a set of any fields for argument matching, including anyInt. So, the "anyInt" that appears inside the expectation block is that field, not the local variable of same name.
(If you are using a decent Java IDE, it should show fields with a different color than that used for local variables, making the mistake easy to spot.)

return void in a void method?

I know I can do this:
void someMethod(){
return;
}
but I get a syntax error on
void someMethod(){
return void;
}
Why is the latter not allowed? It makes more sense to me.
Edit: I know what a void method is, and that I don't have to return from it at all(and probably shouldn't, in most cases) but I don't understand why I can't return void from a void method. In my opinion, there should be no keyword in the method declaration (like constructors) if the you are able to write return;.
I think both are to be shunned. I prefer this:
void someMethod() {
// do stuff; no return at bottom
}
I'd be willing to be that you'd find lots of methods in the JDK source code that look like this.
When you declare a method as void, you're saying that the method does not return a value. Attempting to return a value, therefore, is illegal. Additionally, return void; has a syntax error because void is not (indeed, cannot be) the name of an in-scope variable.
void is a type, not an expression, so trying to write return void is the same as trying to write return int: syntactically invalid.
When you call return void;, you are using a reserved keyword in the incorrect manner. Since it would not expect the keyword void in that manner, it would cause an error.
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.
If you would prefer to return something, then you can return null; by parameterizing a type Void like in this answer, but that's unconventional. Best bet is to omit return altogether or just say return;.
return x; indicates that control is leaving the method and that its result is the value of x.
return; indicates that control is leaving the method without a result.
The type void is a type with zero values, so for void methods there is no x such that return x makes sense.
All non-void methods must do one of three things:
Fail to exit ever.
Finish abnormally with an exception.
Finish normally with zero or one return values.
Since void is the only type with zero possible values (Classes with private uncalled ctors don't count because of null), there is no possible return in a non-void method such that return makes sense.

How to change the value of a boolean var inside a method?

This is maybe so silly.
I have a boolean variable inside the main method. By calling another method of this class or another class I want my boolean value to be modified in the main method. I do this but the change happens only in the called method(locally), not the caller(main). I think this is because of the pass-by-value feature of java.
I even tried Boolean type, but the same problem there!
Actually I'll use this to manage the ordering of concurrent threads. The main processor will check for the boolean value of every thread to see if it is ok to continue and tick the clock. After ticking the clock the main will make the vars false and will wait until the vars are again true. the sub-threads will start their task if the boolean value of them each is false. After the task is done they will make the vars to true so the main processor is able to tick again.
So I want something without a return. I mean as the value is changed inside the method the main could see it.
boolean var = true;
var = methodWhichReturnsTheNewValueOfTheVariable();
and inside the called method:
return newBooleanValue;
or
SomeObjectWithBooleanVariableInside var = new SomeObjectWithBooleanVariableInside(true);
methodWhichModifiesTheObject(var);
and inside the called method:
var.setBooleanValue(newBooleanValue);
A Boolean is such an object: it contains a boolean value. But it's intentionally designed as immutable: its wrapped boolean value can't be changed. So you need to create your own, functional object.
The usual way to do this is the following:
public static void main(String[] args) {
boolean myVar = true;
...
...
myVar = myFunction();
}
public static boolean myFunction() {
// the method should do it's calculation and return the value:
return false;
}
Yes - you cannot modify passed-by-value parameter inside a method in Java (for example in C# you would write method(ref param)).
Why can't you return this value using the method:
public boolean method(params...) {...}
Or you can pass in param the reference to caller:
public void method(params..., CallerClass caller) {
//do something
caller.setValue(Boolean.FALSE);
}
Or you can make this variable accessible in caller and calling method scopes - static variable, etc.
Primitive types are passed by value, so you can't change variables coming as parameter in a method.
This makes also easier to understand how a program works, since this kind of behavior is made more evident in an invocation like this:
boolean prime = false;
prime = isPrime(number);
you can see that found variable is reassigned; while you can assume that number will remain unchanged. This helps in code readability.
There is a dirty trick that sometime can be used. Since arrays are objects, you can use an array to wrap a primitive type:
boolean[] prime = { false };
isPrime(number, result);
public void isPrime(int number, boolean[] result) {
result[0] = true;
}
The object reference is passed by value too, but here we change the content of the array, not the array reference.
This works. But, I don't recommend to design your code like this.
Sometimes, knowing this trick can be useful in unit tests though.
when you think that you changed the value of the primitive boolean it only changed the value in the scope of that method. same with Boolean as it is immutable. changing its value actually assigned a new value to it inside the scope of that method.
you should return the new value from that method and then assign it or you could also use a global boolean that is known to all and to change that one.
(and by the way, if you're dealing with concurrency check out AtomicBoolean)

Refresh Java argument

I am writing a program for a programming game called robocode. The problem is here:
void wallScan(boolean While){
stop();
getStraight();
turnGunRight(90);
if(startabsolute){
straight=true;
}
while (While){
ahead(10000000);
turnRight(90);
}
resume();
}
You might not understand most of the code as it extends robocode.Robot, but my problem is in the variable While. The loop doesn't end as the method gets the argument once and it is true so the method becomes an eternal loop but is there a way to refresh the method argument as I don't want to make a while loop every time I call this method?
You shouldn't write you parameters in capital letters. So it would be while instead of While. However this isn't allowed because while is a keyword. So first change your argument passed in the method.
Then your problem is, that you call the method with the argument. Since it is a primitive boolean value you pass, the value can't be changed from another method, call, class, etc. during the execution of your wallScan method and therefore the while loop never finishes.
Instead you should for example create a member field in the class containing this method an give it a meaningful way. in the example i just call it whileCondition.
void wallScan(){
stop();
getStraight();
turnGunRight(90);
if(startabsolute){
straight=true;
}
while (whileCondition()){
ahead(10000000);
turnRight(90);
}
resume();
}
public void setWhileCondition(boolean bool) {
whileCondition = bool;
}
public boolean isWhileCondition() {
return whileCondition;
}
So you can set the condition which leads to the termination of the while loop from outside your method.
It seems to me that you don't want a single boolean value - you want something which will return you a boolean every time you ask for one. As a simple example:
public interface ContinueChecker {
boolean shouldContinue();
}
(Horrible names, but hopefully you can come up with something better.) You can then write:
void wallScan(ContinueChecker checker) {
...
while (checker.shouldContinue()) {
...
}
}
An alternative form of this would be a generic interface, such as Provider<T> one from Guice:
public interface Provider<T> {
T get();
}
Your method could take a Provider<Boolean> for the same purpose.
Personally I prefer this approach over that of Sebi - it allows your class to represent the state of the board itself (or whatever) - whether one particular robot should stop doesn't feel like it should be part of the same state. It's effectively local to this method, as far as I can see.

Categories