I am new to Java unit testing and started using Mockito. I am using doNothing.... but the real method get always executed. Not sure what I am missing.
public abstract class MyApplication {
private Square s;
private Circle c;
public MyApplication(Square s, Circle c){
this.s = s;
this.c = c;
}
public void firstMethod() {
System.out.println("Starting first Method");
secondMethod();
System.out.println("Ending first Method");
}
public void secondMethod() {
//some business logic here
}
}
public class SmallApplication extends MyApplication {
private Square s;
private Circle c;
public SmallApplication(Square s, Circle c){
this.s = s;
this.c = c;
}
}
public class MyApplicationTest {
public void testFirstMethod() {
Square smock = mock(Square.class);
Circle cmock = mock(Circle.class);
SmallApplication app = new SmallApplication(smock, cmock);
SmallApplication appSpy = spy(app);
doNothing().when(appSpy).secondMethod();
appSpy.firstMethod();
}
}
I donot want seconMethod's business logic to be executed but with the above code the second method business logic is always executed. Please help out.
Related
I have implemented a helper script using a youtube example. But when I use the Resource method in my other scripts the compiler gives an null Reference error. What am I doing wrong.
this is my helper script and how the resources are called.
using UnityEngine;
using System.Collections;
namespace Helper
{
public class Resource
{
public static string AnimatorController = "System/PlayerAnimator";
}
}
The path according to my scene is
Assets/Resources/System/PlayerAnimator.controller
This is how I used in my other scripts to load the resources
private Animator _animator;
private RuntimeAnimatorController _animatorController;
_animatorController = Resources.Load(Resource.AnimatorController) as RuntimeAnimatorController;
_animator.runtimeAnimatorController = _animatorController;
What is the fix for this?
I added both of the scripts. Non didn't work
PlayerCharctor.cs
using UnityEngine; using System.Collections; using Helper;
[RequireComponent(typeof(NetworkView))] [RequireComponent(typeof(CharacterController))] [RequireComponent(typeof(Animator))]
[RequireComponent(typeof(PlayerMotor))] [RequireComponent(typeof(PlayerCamera))]
[AddComponentMenu("Scripts/Player/PlayerCharacter")] public class PlayerCharacter : MonoBehaviour {
#region Variables & Properties (Private)
private CharacterController _controller;
private Animator _animator;
private RuntimeAnimatorController _animatorController;
#endregion
#region Variables & Properties (Public)
public CharacterController Controller
{
get
{
return _controller;
}
}
public Animator Animator
{
get
{
return _animator;
}
}
#endregion
#region Unity Event Funtions
void awake()
{
_animator = GetComponent<Animator>();
_controller = GetComponent<CharacterController>();
}
// Use this for initialization
void Start ()
{
//Ensure networkview Component exists
if (GetComponent<NetworkView>() != null)
{
//Ensure that initialization only executes if this is a valid instance
if (GetComponent<NetworkView>().isMine || Network.peerType == NetworkPeerType.Disconnected)
{
//Load in the AnimatorController at runtime
_animatorController = Resources.Load(Resource.AnimatorController) as RuntimeAnimatorController;
_animator.runtimeAnimatorController = _animatorController;
_controller.center = new Vector3(0f, 1f, 0f);
_controller.height = 1.8f;
}
else
{
enabled = false;
}
}
else
{
Debug.Log("Attach a NetWorkViewComponent!!");
}
}
// Update is called once per frame
void Update ()
{
}
#endregion
#region Methods
#endregion Methods }
AND the Helper script
using UnityEngine;
using System.Collections;
namespace Helper
{
#region Referance Cache
public class PlayerInput
{
public static string Horizontal = "Horizontal";
public static string Vertical = "vertical";
public static string Jump = "Jump";
public static string RightX = "Mouse X";
public static string RightY = "Mouse Y";
}
public class GameTag
{
//System tags
public static string Untagged = "Untagged";
public static string Respawn = "Respawn";
public static string Finish = "Finish";
public static string EditorOnly = "EditorOnly";
public static string MainCamera = "MainCamera";
public static string Player = "Player";
public static string GameController = "GameController";
public static string PlayerCamera = "PlayerCamera";
}
public class Resource
{
public static string AnimatorController= "System/PLController"; //Changed the name of the controller (new one)
}
public static class AnimatorConditions
{
public static string Speed = "Speed";
public static string Direction = "Direction";
public static string Grounded = "Grounded";
public static string AirVelocity = "AirVelocity";
}
#endregion
#region FSM Enumerations (Finite State Machine)
public enum CameraState
{
Normal,
Target
}
public enum SpeedState
{
Walk,
Run,
Sprint
}
#endregion
#region Object Structures
public struct CameraTargetObject
{
private Vector3 position;
private Transform xForm;
public Vector3 Position
{
get
{
return position;
}
set
{
position = value;
}
}
public Transform XForm
{
get
{
return xForm;
}
set
{
xForm = value;
}
}
public void Init(string camName, Vector3 pos, Transform transform, Transform parent)
{
position = pos;
xForm = transform;
xForm.name = camName;
xForm.parent = parent;
xForm.localPosition = Vector3.zero;
xForm.localPosition = position;
}
}
public struct CameraMountPoint
{
private Vector3 position;
private Transform xForm;
public Vector3 Position
{
get
{
return position;
}
set
{
position = value;
}
}
public Transform XForm
{
get
{
return xForm;
}
set
{
xForm = value;
}
}
public void Init(string camName, Vector3 pos, Transform transform, Transform parent)
{
position = pos;
xForm = transform;
xForm.name = camName;
xForm.parent = parent;
xForm.localPosition = Vector3.zero;
xForm.localPosition = position;
}
}
#endregion
}
There is no problem in your code of loading assets from Resources. But in fact it may be because of your _animator variable. I am 99% sure that it is null. First get the Animator component like _animator = GetComponent<Animator>(); then assign its RuntimeAnimatorController.
I'm working in java me. I'm trying to switch between visual designs using ok Commands and back Commands. I have a form displayable which I named formA in my main class A.java and a formB in another class B.java . I used an ok Command in formA which on selection, is supposed to take the user to formB.
I created a reference to B.java in my main class A.java constructor
B b;
// A.java constructor
public A() {
b = new B(this);
}
now I could call the getFormB method from my commandAction in formA. Then I added a backCommand which is supposed to take me back to formA in A.java and I tried creating a reference in B.java same way I did in A.java but I get a SecurityException MIDletManager ERROR at runtime. I was adviced to add an A attribute to my B class and receive the instance as a constructor parameter so I can call the getFormA() method to switch to formA in A.java
A a;
B(A a) {
this.a = a;
}
in command action I did ds on the backCommand:
switchDisplayable ( null , a.getFormA());
This compiled, but at runtime on hitting the BACK key from formB I get java/lang/NullPointerException.
Can anyone tell me why this happended and how to fix it please. All I'm trying to acheive is the backCommand to take the user back to formA from formB
If your A class extends Form or your A class is Displayable, then in the Back command, you can just tell switchDisplayable(null, a).
If your A class is not a Form, then make sure your A class has the following methods:
public Form getFormA() {
return ...; // return the `Form` here so you will not get NullPointerException
}
UPDATE:
If you're using NetBeans, you can open Flow tab and drag backCommand from formB to formA. NetBeans will generate the required code for you.
If you code by hand, then it will looks like the following:
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA;
private Form formB;
private Command formA_next;
private Command formB_back;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new Form("Form A");
formA_next = new Command("Next", Command.SCREEN, 0);
formA.addCommand(formA_next);
formA.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formA_next) {
display.setCurrent(formB);
}
}
});
formB = new Form("Form B");
formB_back = new Command("Back", Command.BACK, 0);
formB.addCommand(formB_back);
formB.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c==formB_back) {
display.setCurrent(formA);
}
}
});
}
display.setCurrent(formA);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
I don't know how you code your Form, but it seems that a is null. Maybe you can show me the full code. Passing this in constructor is generally not recommended. By the way, you still need a 'main' class that extends MIDlet right? Then there will be 3 classes, such as:
ExampleMiddlet.java (this is where you put your MIDlet lifecycle, such as startApp(), pauseApp(), etc):
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ExampleMidlet extends MIDlet {
private Display display;
private Form formA, formB;
public void startApp() {
if (display==null) {
display = Display.getDisplay(this);
formA = new FormA(this);
formB = new FormB(this);
}
display.setCurrent(formA);
}
public Form getFormA() {
return formA;
}
public Form getFormB() {
return formB;
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
FormA.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormA extends Form {
private Command cmdNext;
public FormA(final ExampleMidlet midlet) {
super("Form A");
append("This is form A.");
cmdNext = new Command("Next", Command.SCREEN, 0);
addCommand(cmdNext);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormB());
}
});
}
}
FormB.java (this is where you put the content of your Form):
import javax.microedition.lcdui.*;
public class FormB extends Form {
private Command cmdBack;
public FormB(final ExampleMidlet midlet) {
super("Form B");
append("This is form B.");
cmdBack = new Command("Back", Command.SCREEN, 0);
addCommand(cmdBack);
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
Display.getDisplay(midlet).setCurrent(midlet.getFormA());
}
});
}
}
i have one doubt if if we have two classes with same method,object of class doesnt know which method to call this situtation we use interface? but how interface know which class method to call,how to apply interface ,i have some code plz check and tell me?
namespace IntExample
{
interface Iinterface
{
public void add();
public void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
}
}
An interface is an abstraction, one that allows you to perform polymorphism without the need for inheritance. As such, an "interface variable" holds an instance of a concrete class, and the current instance's class is always used for method lookups by the interface as long as the variable contains that instance.
Pretty straightforward question. I am using Jersey to build a REST system. If I have a class with a value that I need to use during processing but don't want sent as part of the XML or JSON output when the class is marshaled, is there a way to ignore it? Something like:
#XmlRootElement(name="example")
class Example {
private int a;
private String b;
private Object c;
#XmlElement(ignore=true)
public int getA() { return a; }
#XmlElement
public String getB() { return b; }
#Ignore
public Object getC() { return c; }
... //setters, constructors, etc.
}
I would hope that something like the ignore=true over getA() or the #Ignore over getC() would work, but i can find no documentation.
There are couple options depending on how many fields/properties you want to be ignored.
Option #1 - #XmlTransient
If you want less than half of the properties to be ignored then I would recommend annotating them with #XmlTransient. This will exclude them from the XML mapping.
#XmlRootElement
class Example {
private int a;
private String b;
private Object c;
#XmlTransient
public int getA() { return a; } // UNMAPPED
public String getB() { return b; } // MAPPED
#XmlTransient
public Object getC() { return c; } // UNMAPPED
... //setters, constructors, etc.
}
Option #2 - #XmlAccessorType(XmlAccessType.NONE)
If you want more than half of the properties ignored I would recommend using the #XmlAccessorType annotation at the type level to set XmlAccessType.NONE. This will cause only annotated properties to be mapped to XML.
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
class Example {
private int a;
private String b;
private Object c;
public int getA() { return a; } // UNMAPPED
#XmlElement
public String getB() { return b; } // MAPPED
public Object getC() { return c; } // UNMAPPED
... //setters, constructors, etc.
}
For More Information
http://blog.bdoughan.com/2012/04/jaxb-and-unmapped-properties.html
How can I cancel a thread from another class fetching/refreshing location. I am able to cancel a thread from within the same class. But I am unable to do this across classes. Declaring the GPSThread static did not help. Can anyone please guide?
Class1:
public class GPSListener {
/* Other instantiation code */
Dialog busyDialog1 = new Dialog("Refreshing Location...",
new String [] { "Cancel" },
new int [] { Dialog.CANCEL},
Dialog.CANCEL,
Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS))
{
public void fieldChanged(Field field1, int context1)
{
GPSHandler.requestStop();
busyDialog1.cancel();
}
};
public String refreshCoordinates() {
String test = "nothing";
if (GPSHandler.isStopRequested())
{
GPSHandler.stopRequested = false;
return null;
}
GPSHandler.getInstance().setListener(this);
GPSHandler.getInstance().requestLocationUpdates();
if (GPSHandler.isStopRequested())
{
GPSHandler.stopRequested = false;
return null;
}
busyDialog1.setEscapeEnabled(false);
busyDialog1.show();
return test;
}
public void onLocationReceived(Coordinates location) {
lblLatitude.setText(Double.toString(location.getLatitude()));
lblLongitude.setText(Double.toString(location.getLongitude()));
busyDialog1.cancel();
}
}
Class 2:
public class GPSHandler {
private GPSThread _gpsThread;
private Coordinates _location;
private boolean _gotLocation;
private GPSListener _listener;
/** this class will be a Singleton, as the device only has one GPS system */
private static GPSHandler _instance;
/** #return the Singleton instance of the GPSHandler */
public static GPSHandler getInstance() {
if (_instance == null) {
_instance = new GPSHandler();
}
return _instance;
}
public static boolean stopRequested = false;
public synchronized static void requestStop() {
stopRequested = true;
}
public synchronized static boolean isStopRequested() {
return stopRequested;
}
/** not publicly accessible ... use getInstance() */
private GPSHandler() {
}
/** call this to trigger a new location fix */
public void requestLocationUpdates() {
if (_gpsThread == null || !_gpsThread.isAlive()) {
_gpsThread = new GPSThread();
_gpsThread.start();
}
}
public void setListener(GPSListener listener) {
// only supports one listener this way
_listener = listener;
}
private void setLocation(final Coordinates value) {
_location = value;
if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
_gotLocation = true;
if (_listener != null) {
// this assumes listeners are UI listeners, and want callbacks on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_listener.onLocationReceived(value);
}
});
}
}
}
private class GPSThread extends Thread {
private void getLocationFromGoogle() {
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
writeDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
final int code = dataInputStream2.readInt();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(code + "");
}
});
if (code == 0) {
final double latitude = dataInputStream2.readInt() / 1000000D;
final double longitude = dataInputStream2.readInt() / 1000000D;
setLocation(new Coordinates(latitude, longitude, 0.0f));
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(latitude+"-----"+longitude);
}
});
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private void tryGetLocationFromDevice() {
_gotLocation = false;
try {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
setLocation(myLocation.getQualifiedCoordinates());
} catch ( InterruptedException iex ) {
System.out.println(iex.getMessage());
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
if (!_gotLocation) {
getLocationFromGoogle();
}
}
public void run() {
int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); // OS 4.5 - 6.0
int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0
if (bbMapsHandle > 0 || bbMapsHandle60 > 0) {
tryGetLocationFromDevice();
} else {
getLocationFromGoogle();
}
}
}
private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
Your GPSThread object is currently declared as a private inner class within GPSHandler. If you want to stop execution (or indeed do anything with it) from outside the scope of GPSHandler you will need to mark it as public. You will also need to provide some public mechanism (e.g. a stop() method) to cancel the thread execution.
The most common way of doing this is to have a boolean flag inside your thread (e.g shouldStop) which is checked within your main execution loop inside run() to see if it should stop. When the stop() method is called shouldStop is set to true and your Thread will stop.
Here's a good example: How to stop threads in Java?
There's two groups of changes you should make.
Change the Stop Requested Flag
First, remember that encapsulation is a good thing in Object-Oriented languages. The isStopRequested() method, or stopRequested variable of the GPSHandler should not be used outside of that class. Your UI's GPSListener should not attempt to use either of those. I would change your GPSHandler to use this:
private static boolean stopRequested = false;
public synchronized static void requestStop() {
stopRequested = true;
}
private synchronized static boolean isStopRequested() {
return stopRequested;
}
Only requestStop() should be public. It looks like you made stopRequested public to allow the GPSListener to reset it. If it needs resetting, let the class that owns that variable do the resetting. For example, in GPSHandler:
/** call this to trigger a new location fix */
public void requestLocationUpdates() {
if (_gpsThread == null || !_gpsThread.isAlive()) {
// reset this stop flag:
stopRequested = false;
_gpsThread = new GPSThread();
_gpsThread.start();
}
}
requestLocationUpdates() is really the method that starts the thread, so it should be where stopRequested gets reset to false.
Also, another reason that you should not make stopRequested public and allow other classes to use it is that this is not generally thread-safe. One of the reasons to wrap stopRequested with the requestStop() and isStopRequested() methods is to add thread-safety. There's many ways to do that, but those two methods achieve thread-safety by being marked with the synchronized keyword.
Change How/Where You Check the Flag
After you make these fixes, you need to change where you check if a stop has been requested. You don't really want to check isStopRequested() in the refreshCoordinates() method. That method involves almost no work. Even though it starts the process of getting a location fix, that only starts a thread, but the actual work of getting the location is done on a background thread (your GPSThread). If requestStop() is called, it's very unlikely that it will be called in the middle of refreshCoordinates(), so that's not where you should check it.
Check isStopRequested() multiple times within the GPSHandler class's methods tryGetLocationFromDevice() and getLocationFromGoogle(). Those are the methods that perform slow processing. Those are the ones you might want to interrupt in the middle. So, something like this:
private void getLocationFromGoogle() {
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
if (isStopRequested()) return;
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
writeDataGoogleMaps(outputStream2, cellID, lac);
if (isStopRequested()) return;
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
if (isStopRequested()) return;
final int code = dataInputStream2.readInt();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(code + "");
}
});
And in tryGetLocationFromDevice(), you could do this (make sure to add the member variable and new method below):
private LocationProvider _locationProvider; // must be a member variable!
public void requestStop() {
if (_locationProvider != null) {
// this will interrupt the _locationProvider.getLocation(300) call
_locationProvider.reset();
}
}
private void tryGetLocationFromDevice() {
_gotLocation = false;
try {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
_locationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = _locationProvider.getLocation(300);
setLocation(myLocation.getQualifiedCoordinates());
} catch ( InterruptedException iex ) {
// this may be caught if stop requested!!!!
System.out.println(iex.getMessage());
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
if (!_gotLocation && !isStopRequested()) {
getLocationFromGoogle();
}
}
Then, call the GPSThread.requestStop() method from the outer GPSHandler.requestStop() method:
public synchronized static void requestStop() {
stopRequested = true;
if (_gpsThread != null) {
_gpsThread.requestStop();
}
}