Could someone create a JUnit test in NetBeans for the code that I have pasted below? I'm not quite sure what to do once I've created the actual test.
package prog3;
import java.util.ArrayList; import java.util.Iterator;
public class MedicineClass
{
private String MedicineName;
private int MedicineRegNum;
private ArrayList RelatedMedicine;
public MedicineClass(String newMedicineName, int newMedicineRegNum)
{
newMedicineName = MedicineName;
newMedicineRegNum = MedicineRegNum;
RelatedMedicine = new ArrayList();
}
public void setMedicine(String newMedicineName)
{
newMedicineName = MedicineName;
}
public String getMedicineNameAndNum()
{
return "Medicine Registration Number: " + MedicineRegNum + "Medicine Name: " + MedicineName;
}
public void Medicine(Medicine Drug)
{
RelatedMedicine.add(Drug);
}
public void addMedicine(String newMedicineName, int newMedicineRegNum)
{
Medicine temp = new Medicine(newMedicineName, newMedicineRegNum);
RelatedMedicine.add(temp);
}
public void listAllMedicines()
{
StringBuilder sb = new StringBuilder();
Iterator lst = RelatedMedicine.iterator();
while (lst.hasNext())
{
Medicine temp = (Medicine)lst.next();
sb.append(temp.getNameandRegNum());
sb.append("\n");
}
System.out.println(sb.toString());
}
}
You have the class that you need to write JUnit tests for. Read this: Writing JUnit Tests in NetBeans IDE and Introduction to Unit Testing
I suggest using the "create JUnit test" button in the IDE. This will place the class in the right place for you. You can then copy'n'paste your code into that test. If that button is not visible on your toolbar, right-click on your toolbar and add that button from the customise menu. I also recommend adding the "test this class" button.
There are numerous APIs that claim to automate this process. Perhaps one of them would be helpful for you:
http://sourceforge.net/projects/amaticjunittool/
http://sourceforge.net/projects/junitgenerator/
http://sourceforge.net/projects/junittestmaker/
http://sourceforge.net/projects/spike-test-gen/
Related
I've recently taken on a new job and they are requiring me to get to grips with Java.
I'll be using Java and Selenium Webdriver to automate test cases etc.
To throw myself into the java/Webdriver world, I bought this book, Mastering Selenium Webdriver.
When going through the book we get to a section on making the tests run in parellel and I'm asked to create two new classes.
DriverFactory.java and WebDriverThread.java
Once i've made all the changes and go to build, and run my tests with maven. using the following command in the cmdline.
mvn clean install
I get the following error
#Override method does not override method from superclass
I've had a google around and I'm not really sure how to fix the issue. The book is assuming some Java experience that I just don't have yet.
below are the two classes in full that I've since created.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class WebDriverThread {
private WebDriver webDriver;
private final String operatingSystem =
System.getProperty("os.name").toUpperCase();
private final String systemArchitecture =
System.getProperty("os.arch");
public WebDriver getDriver() throws Exception {
if (null == webDriver) {
System.out.println(" ");
System.out.println("Current Operation System: " + operatingSystem);
System.out.println("Current Architecture: " + systemArchitecture);
System.out.println("Current Browser Selection: FireFox");
System.out.println(" ");
webDriver = new FirefoxDriver(DesiredCapabilities.firefox());
}
return webDriver;
}
public void quitDriver() {
if (null != webDriver) {
webDriver.quit();
webDriver = null;
}
}
}
And here is the second class created,
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeSuite;
public class DriverFactory {
private static ThreadLocal<WebDriverThread> driverThread;
#BeforeSuite
public static void instantiateDriverObject() {
driverThread = new ThreadLocal<WebDriverThread>() {
#Override
protected WebDriverThread InitialValue() {
WebDriverThread webDriverThread =
new WebDriverThread();
return webDriverThread;
}
};
}
public static WebDriver getDriver() throws Exception {
return driverThread.get().getDriver();
}
#AfterMethod
public static void quitDriver() throws Exception {
driverThread.get().quitDriver();
}
}
The error is one the #Override line. I've read that it's something to do with not implementing a class from the class it's inheriting from?
I'm then calling the this all from this line in the actual test.
WebDriver driver = DriverFactory.getDriver();
I think i've tried to walk before I could crawl, but i thought getting this book would give me a jump up for the new job.
any help would be appreciated.
Thanks.
I'm just getting into testing of code. I have done unit tests before but haven't really isolated them. So they were more like integration test (indirectly). I want to give Mockito a try and I have added it to my Intellij IDE.
But I have no idea of how to actually implement mocking at all. There are examples on their website but I just can't wrap my head around the concept of mocking. I know that one uses mocking to isolate the unit testing to ensure that the errors are in the unit itself and not in a dependency.
I wrote the following:
#Test
public void testChangeMemberReturnsTrue() throws Exception {
Member tempMem = new Member();
tempMem.setMemberFirstName("Swagrid");
tempMem.setMemberLastName("McLovin");
tempMem.setMemberID("SM666");
SQLDUMMY.saveMember(tempMem); //Save member to dummy DB.
Member checkMem = new Member();
ArrayList<Member> memArr = SQLDUMMY.getAllMembers();
for (Member m : memArr) { // Look through all saved members
if (m.equals(tempMem)) { // If match, save to checkMem
checkMem = m;
}
}
assertTrue(tempMem.equals(checkMem)); // Make sure they are really equal.
String newfirstname = "Darius";
String newlastname = "DunkMaster";
assertTrue(memhandling.changeMember(tempMem, newfirstname, newlastname));
}
And here is the actual method:
public boolean changeMember(Member mem, String n1, String n2) {
try {
ArrayList<Member> memArr = SQLDUMMY.getAllMembers();
for (Member m : memArr) {
if (m.equals(mem)) {
m.setMemberFirstName(n1);
m.setMemberLastName(n2);
m.setMemberID(ensureUniqueID(m, m.getMemberID())); //Just a method call to another method in the same class to ensure ID uniqueness.
return true;
}
else {
return false;
}
}
}
catch (Exception e) {
System.out.println("Error4.");
}
return false;
}
I'd like to mock the SQLDUMMY (Which I created just to see if my tests would pass at all, which they do.) The SQLDUMMY class looks like this:
public class SQLDUMMY {
private static ArrayList<Member> memberList = new ArrayList<>();
private static ArrayList<Ship> shipList = new ArrayList<>();
public static ArrayList<Member> getAllMembers() {
return memberList;
}
public static void saveMember(Member m) {
memberList.add(m);
}
public static void deleteMember(Member memIn) {
memberList.remove(memIn);
}
public static void saveShip(Ship newShip) {
shipList.add(newShip);
}
public static ArrayList<Ship> getAllShips() {
return shipList;
}
public static void deleteShip(Ship s) {
shipList.remove(s);
}
}
It basically just consists of getters and add/remove for the ArrayLists that act as a contemporary DB storage.
Summary: How can I mock the SQLDUMMY class (DAO), so it is no longer a dependency for the Unit tests?
You need to read on how Mockito works.
The basic idea is that it extends you class and and overrides all methods and allows you to return what ever you want it too.
Syntax is :
SQLDummy sqlDummy = Mockito.mock(SQLDummy.class);
Mockito.when(sqlDummy.getAllShips()).thenReturn(new ArrayList< Ship >())
I need to produce two separate jar files, both interact with each other but do different things. I have two projects loaded into Eclipse, but both use a lot of the same imports, and so I have them in subfolders under the same workspace.
One of them gets "java class xxxxcould not be found" when I try to run it.
As I attempted to fix that, I was comparing the two projects and noticed that a folder was part of the external build path of the working one, but not the non-working one. I added it to the non-working one and broke the working one.
The one that had been working now has an error on the main class name. I call the program ZSTATEngine, and so the class is
public class ZSTATEngine implements ETOSFilterEngine
Now that name is highlighted and when I mouse over it is says:"the type ZSTATEngine must implement the inherited abstract method ETOSFilterEngine.doFilter(MessageBlock)"
What could have changed? It was working fine before, and nothing in the code itself changed. I don't understand how the referenced libraries work, but it at least appears nothing changed in their structure in the formerly-working project.
Ok some further information: I do actually have a section within that class:
public MessageBlock doFilter(MessageBlock msgBlock)
so I am implementing that method... but that method has an error inside of it now,
"The method addFilteredMessage(MessageBlock) in the type FilterFramework is not applicable or the arguments (MessageBlock) ...
How could that have gone bad? It was working fine too.
Here's the full code:
package com.ibm.tpf.internal;
import java.awt.Color;
/*import java.util.ArrayList;*/
/*import java.util.*;*/
import com.ibm.tpf.etos.TPFFilter.*;
//import com.ibm.tpf.etos.TPFFilter.TernarySwitch;
import com.ibm.tpf.etos.api.*;
/*
import com.ibm.tpf.etos.api.Constants;
import com.ibm.tpf.etos.api.MessageBlock;
*/
import com.ibm.tpf.etos.filter.*;
/*
import com.ibm.tpf.etos.filter.ETOSFilterEngine;
import com.ibm.tpf.etos.filter.FilterConfigurationException;
import com.ibm.tpf.etos.filter.FilterFramework;
import com.ibm.tpf.etos.filter.FilterRuntimeException;
*/
public class ZSTATEngine implements ETOSFilterEngine {
FilterFramework fw = null;
String[] names = null;
public ZSTATEngine(FilterFramework filFW, String[] parms) {
super();
this.fw = filFW;
}
/* AAES0009I 13.45.01 FROM TA 05 : AUTC0000I TOSFCOLOR_GREEN TOSBCOLOR_NONE TOSHOLD_0 TOSSAVE_0 TOSALERT_0 AUTC1111I 12.04.41 OK */
public MessageBlock doFilter(MessageBlock msgBlock) throws FilterRuntimeException {
if(msgBlock.getMsgID().equals("AAES0009I")) { /* only handle messages that start with AAES0009I */
if(msgBlock.getMsg().indexOf("ZUVRT") != -1) { /* if the message contains "ZUVRT" then let it through. We want to react to the result of it, not the ZUVRT itself. */
return msgBlock;
}
if(msgBlock.getMsg().indexOf("AUTC0000I") != -1) { /* search string to see if "AUTC0000I is in it. If it is then do..." */
String myString = msgBlock.getMsg();
Color fColor = Color.WHITE; /* set default colors */
Color bColor = Color.BLACK;
msgBlock.setSuppressed(TernarySwitch.ON); /* suppress original message to display new one */
String[] myStringParts = myString.split("\\s+",13); /* divide message into 13 parts. The 13th part is everything remaining. */
String finalPart = myStringParts[12].toString(); /* print last part to the screen */
MessageBlock mb = new MessageBlock(finalPart, Constants.ETOS_ONE_MSG);
String fColorMsg = myStringParts[7].toString(); /* Process the foreground color portion */
if (!fColorMsg.contains("NONE")) {
fColor = ColorStringInterpreter(fColorMsg);
mb.setForeground(fColor);
}
String bColorMsg = myStringParts[8].toString(); /* Process the background color portion */
if (!bColorMsg.contains("NONE")) {
bColor = ColorStringInterpreter(bColorMsg);
mb.setBackground(bColor);
}
String holdMsg = myStringParts[9].toString(); /* Process the hold message portion */
if (holdMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, grab only the number at the end */
String[] holdPart = holdMsg.split("_",2);
if (holdPart[1].toString().equals("1")) {
mb.setHeld(TernarySwitch.ON);
}
}
else {
if (holdMsg.equals("1")) { /* otherwise, just use the number */
mb.setHeld(TernarySwitch.ON);
}
}
String saveMsg = myStringParts[10].toString(); /* Process the save areas. These have two formats currently: TOSSAVE_X_X_X_X and BBBBBBBBB, where X is a digit 1-32, and B is binary. */
if (saveMsg.toUpperCase().startsWith("TOS")) {
String[] savePart = saveMsg.split("_"); /* handle the multiple digit save areas, and ignore the first split which is TOSSAVE */
if (!savePart[1].toString().equals("0")) {
long areaBits = 0;
for (int i=1; i<savePart.length; i++) {
areaBits |= 1L << Integer.parseInt(savePart[i]);
}
mb.setSave(areaBits);
}
}
else { /* otherwise, just use the binary string directly */
long areaBits = Long.parseLong(myStringParts[10].toString(), 2);
mb.setSave(areaBits);
}
fw.addFilteredMessage(mb); /* this is the command that pieces the whole message together */
}
}
int plusLocation = msgBlock.getMsg().lastIndexOf('+');
if (plusLocation > 0) {
MessageBlock mb1 = new MessageBlock(msgBlock.getMsg(), msgBlock.getFlag());
fw.addFilteredMessage(mb1);
msgBlock.setSuppressed(TernarySwitch.ON);
MessageBlock mb2 = new MessageBlock("", Constants.ETOS_ONE_MSG);
fw.addFilteredMessage(mb2);
}
return msgBlock; /* whatever gets returned is what the system prints */
}
private Color ColorStringInterpreter(String colorMsg) throws FilterRuntimeException {
if (colorMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, then we're using color names */
String[] colorParts = colorMsg.split("_",2);
String colorTxt = colorParts[1].toString().trim();
if (colorTxt.toUpperCase() != "NONE") {
Color finalColor = Colors.fromString(colorTxt);
return finalColor;
}
}
else {
String[] colorParts = colorMsg.split("_",3); /* otherwise we're using RGB values */
String sRed = colorParts[0].toString().trim();
String sGreen = colorParts[1].toString().trim();
String sBlue = colorParts[2].toString().trim();
/*mb = new MessageBlock(sRed, Constants.ETOS_ONE_MSG);*/
int iRed = Integer.parseInt(sRed);
int iGreen = Integer.parseInt(sGreen);
int iBlue = Integer.parseInt(sBlue);
Color finalColor = new Color (iRed, iGreen, iBlue);
return finalColor;
}
return null;
}
public String getName() {
return null;
}
public void modifyState(Object[] newParams) throws FilterConfigurationException, FilterRuntimeException {
}
public boolean isActive() {
return false;
}
public void shutdown() {
}
}
public class ZSTATEngine implements ETOSFilterEngine
According to above code, your class ZSTATEngine is implementing an interface ETOSFilterEngine, which means your class need to implement all the abstract methods of ETOSFilterEngine.
From Java doc:
Interfaces form a contract between the class and the outside world,
and this contract is enforced at build time by the compiler. If your
class claims to implement an interface, all methods defined by that
interface must appear in its source code before the class will
successfully compile.
Check the link: http://www-01.ibm.com/support/knowledgecenter/SSB23S_1.1.0.9/com.ibm.tpfops.doc_1112/aaeo1/fengapi.html?cp=SSB23S_1.1.0.9%2F2-3-10-3
Below are the 5 methods that are present in ETOSFilterEngine, which you need to implement.
public MessageBlock doFilter (MessageBlock) throws
FilterRuntimeException;
public void modifyState (Object[ ]) throws
FilterConfigurationException,
FilterRuntimeException;
public boolean isActive();
public void shutdown();
public String getName();
Above link has a code example on how to properly implement this interface. You can see that the class ZSTATEngine in the example is implementing all the 5 methods provided by ETOSFilterEngine.
Check the type of MessageBlock in your imports, it should be import
com.ibm.tpf.etos.api.MessageBlock; I can see that you have commented your import which is wrong.
Uncomment the line : import com.ibm.tpf.etos.api.MessageBlock;
AS mentioned by "Jakub Zaverka" perhaps you have two versions in classpath or build path. Check the jar order, whether is picking the right class... It will happen even if no code has changed.
One way to find it out is, just do an F3 on ETOSFilterEngine and click "Link with editor" option in package explorer. It will show the .class file and the jar from which its picked up.. If its from the wrong jar or old jar, just go to Project>Properties>Build Path>Order and Export and change the order of the right jar to the top, by clicking on Top button..
I need to create a custom function in Jmeter, and because of performance issues I can't use beanshell.
I wrote a java class following http://gabenell.blogspot.com/2010/01/custom-functions-for-jmeter.html and http://code4reference.com/2013/06/jmeter-custom-function-implementation/, but when I compile it I can't seem to get Jmeter to recognize it.
My class:
package custom.functions;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class Username extends AbstractFunction{
private static final List<String> desc = new LinkedList<String>();
private static final String KEY = "__Username";
private int number = 0;
static {
desc.add("Pass a random value to get a valid username for the system.");
}
public Username() {
super();
}
#Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
try {
return getValue(number);
} catch(Exception e){
throw new InvalidVariableException(e);
}
}
public String getValue(int number){
return "John-Smith";
}
#Override
public synchronized void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
checkParameterCount(parameters, 1, 1);
Object[] values = parameters.toArray();
number = Integer.parseInt(((CompoundVariable) values[0]).execute().trim());
}
#Override
public String getReferenceKey() {
return KEY;
}
#Override
public List<String> getArgumentDesc() {
return desc;
}
}
When I run jar tf custom-functions.jar (to verify that the class file is in the jar):
META-INF/
META-INF/MANIFEST.MF
custom/
custom/functions/
custom/functions/Username.class
I placed the jar in my jmeter lib/ext directory and tried running jmeter by itself and with -Jsearch_paths=../lib/ext/custom-functions.jar, but either way when I open the function helper tool it's not listed, and a simple test plan to verify the function sends instead %24%7B__Username%281%29%7D.
Am I not putting the file in the right place? Is it named incorrectly?
You can put groovy-all.jar on the classpath of Jmeter, and then you will be able to run external .groovy scripts or you can add a JSR223-Groovy Sampler.
My problem was that I had compiled my class using Java 8 instead of Java 7, which was the runtime I was using for jmeter.
I am creating a test suite for my android application and have this setUp method
private static final String TAG_NAME = "TESTING_SUITE";
public TestingMusicDAO musicDAO;
public List<Song> songs;
public Instrumentation instr;
MusicService musicService;
#Override
public void setUp() throws Exception {
instr = this.getInstrumentation();
Log.d(TAG_NAME, "Setting up testing songs");
musicDAO = new TestingMusicDAO(instr.getContext());
musicService = new MusicServiceImpl(musicDAO);
musicDAO.getAllSongsFromFile();
songs = musicDAO.getAllSongs();
for(Song song : songs)
Log.d( TAG_NAME, song.toString() );
}
And then have these tests which are created by a python tool from a text file
public void test1() {
List<Song> testPlaylist;
String testArtist = ("The Beatles");
String actualArtist = ("TheBeatles");
testPlaylist = testingPlaySongsByKeyword(testArtist);
if(testPlaylist.isEmpty()){
fail("No Songs Were Found");
} else {
for( Song loopsongs : testPlaylist){
if (!(loopsongs.getArtist().equals(actualArtist))){
fail("Song Doesnt Contain the artist" + actualArtist + "... Contains ->" + loopsongs.getArtist());
}
}
}
}
and every time one of these gets called the musicDAO is regenerated. How can I stop the setup method from being called
You don't. The design of JUnit is that setUp() and tearDown() are done once per test. If you want it done per class, do it in the constructor. Just make sure that you don't alter anything inside the classes. The reason for doing it once per test is to make sure all tests start with the same data.
You could use #BeforeClass and #AfterClass annotations from JUnit.
#BeforeClass
public static void test_setUp_Once(){
// Code which you want to be executed only once
createDb();
}
#AfterClass
public static void test_tearDown_Once(){
// Code which you want to be executed only once
deleteDb();
}
Note: You need to declare these methods static to work properly.
I had the same basic problem. I want to be able to test the structure of my database, so I create it in the setUp method and delete it in the tearDown. Using the constructor wouldn't solve my need to delete the database once all my tests are executed, so I used some reentrant logic:
static int testsExecutedSoFar = 0;
static boolean isFirstRun = true;
#Override
protected void setUp() throws Exception {
if(isFirstRun){
createDb();
isFirstRun = false;
}
}
#Override
protected void tearDown() throws Exception{
testsExecutedSoFar++;
if (testsExecutedSoFar == totalNumberOfTestCases())
deleteDb();
}
private int totalNumberOfTestCases() {
return countTestCases()+1; //have to add one for testandroidtestcasesetupproperly added by AndroidTestCase
}
The fields have to be static since JUnit creates a new instance of the class for each run. The magic 1 had to be added since AndroidTestCase adds it's own test (testandroidtestcasesetupproperly) to the test suite but it doesn't count towards the number returned by countTestCases().
A bit on the ugly side, but it did the trick.