JUnit - Test Max Number of Objects Created - java

I have a very small class, BuildThreeObjects, which creates a maximum of 3 Objects using a private int variable, numObjects, to store the count. If the count is < 3, a new Object is returned else null is returned.
Could anyone guide me on how to test if a maximum of 3 Objects are created using JUnit. Looking at the API didn't help much. I assumed assertNotNull or assertNull would be used but I can't think how to.
// Code for BuildThreeObjects class
public class BuildThreeObjects {
private int numObjects = 0;
public Object buildObject() {
if (numObjects<3) {
numObjects++;
return new Object();
}
else return null;
}
}
// Code within the JUnit class; all unnecessary code omitted
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
}
// assertNotNull passes and assertNull fails as it only checks the first object creation

You mean something like this?
class BuildThreeObjects{
int count = 0;
public Object buildObject(){
if(count >= 3){
return null;
} else {
count++;
return new Object();
}
}
}
private BuildThreeObjects bto;
#Before
public void setUp() throws Exception {
bto = new BuildThreeObjects();
}
#Test
public void testBuild() {
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNotNull(bto.buildObject());
System.out.println(bto.count);
assertNull(bto.buildObject());
System.out.println(bto.count);
}
// with for loop
for(int i=0; i < 100; i++){
if(i < 3){
assertNotNull(bto.buildObject());
System.out.println(bto.count);
} else {
assertNull(bto.buildObject());
System.out.println(bto.count);
}
}

Just literally do it:
assertNotNull(createObject());
assertNotNull(createObject());
assertNotNull(createObject());
assertNull(createObject());
you could use for-loop also if it could be more expressive.

Related

Non-deterministic behavior with Java Multithreading

I wrote a simple program that I am using to practice multithreading in Java. The goal is to test whether or not a Sudoku solution is valid: No repeating numbers in rows, columns, or sub-grids. At this point I don't care that the entries must be from 1-9. The program works fine when the Sudoku solution is invalid. When the Sudoku solution is valid (on the same input), the program works only sometimes. Specifically, "win" may or may not be printed.
My program works by creating RowThread, ColumnThread, and GridThread. Each are of them check whether the solution has valid rows, columns and grids, respectively. When a thread is finished checking, it calls the appropriate setter method in SudokuTest, which will call the end method in Main if the solution is invalid. If the thread does not determine that the solution is invalid, the setter method will record that the row, column, or grid has been checked, and then call the allChecked method. allChecked checks if row, column, and grid have been checked. If so, then the solution is valid, so it calls Main.success(), which should print "win." Here is my Main class:
public class Main{
public static void end(){//called by SudokuTest when the solution is invalid
System.out.println("fail");
System.exit(0);
}
public static void success() {//called by SudokuTest when the solution is valid
System.out.println("win");/*this line will not always print,
but it is reached in the debugger when I set a breakpoint.*/
System.exit(0);
}
public static void main(String[] args) {
int[][] sudokuSolution = new int[9][9];
int k = 0;
for (int i = 0; i < 9; i++) { //loop fills up a 2d array with the numbers 0-80, a valid solution
for (int j = 0; j < 9; j++) {
sudokuSolution[i][j] = k;
k++;
}
}
//sudokuSolution[1][1] = 0;//Testing an invalid solution
SudokuTest t = new SudokuTest();//
Runnable r = new RowThread(sudokuSolution, t);
Runnable c = new ColumnThread(sudokuSolution, t);
Runnable g = new GridThread(sudokuSolution, t);
new Thread(r).start();
new Thread(c).start();
new Thread(g).start();
}
}
My RowThread class:
public class RowThread implements Runnable {
int[][] _sudoku;
SudokuTest _t;
public RowThread(int[][] sudoku, SudokuTest t) {
_sudoku = sudoku;
_t = t;
}
private void isFail() { //issue: how to get this info back to my Main function?
for(int i = 0; i < _sudoku.length; i++) {
for(int j = 0; j< _sudoku.length; j++) {
for (int k = j+1; k< _sudoku.length; k++) {
if (_sudoku[i][j] == _sudoku[i][k]) {
_t.setRow(true);
return;
}
}
}
}
_t.setRow(false);
}
#Override
public void run() {
isFail();
}
}
My ColumnThread and GridThread classes are the same as RowThread, except for the logic in the isFail() method.
My SudokuTest class:
public class SudokuTest {
public boolean _rowBad;
public boolean _colBad;
public boolean _gridBad;
public boolean _rowChecked;
public boolean _colChecked;
public boolean _gridChecked;
public SudokuTest(){
}
public void setRow(boolean b) {
_rowBad = b;
_rowChecked = true;
if (b) {
Main.end();
}
}
public void setCol(boolean b) {
_colBad = b;
_colChecked = true;
if (b) {
Main.end();
}
}
public void setGrid(boolean b) {
_gridBad = b;
_gridChecked = true;
if (b) {
Main.end();
}
allChecked();
}
public void allChecked() {
if (_gridChecked && _colChecked && _rowChecked) {
Main.success();
}
}
}
Answer: as Maarten Bodewes pointed out, my mistake was to not call allChecked in setCol and setRow.

java.lang.NoSuchFieldException

Our professor assigns us exercises through the jarpeb sytsem (Java Randomised and Personalised Exercise Builder). So the variables names are random.
public class Eczema extends Thread {
private int aurite;
private int[] serlvulate;
public Eczema(int[] serlvulate) {
this.serlvulate = serlvulate;
}
public int getAurite () {
return aurite;
}
#Override
public void run () {
try {
aurite = Integer.MAX_VALUE;
for (int i = 0; i < serlvulate.length; i++) {
if (i < this.aurite) {
this.aurite = i;
sleep (1000);
}
}
} catch (InterruptedException e) {
System.out.println("Found an Exception!");
return;
}
}
}
public class Stub {
public static int polytoky (int[]a, int[]b) throws InterruptedException {
Eczema Eczema1 = new Eczema (a);
Eczema Eczema2 = new Eczema (b);
Eczema1.start();
Eczema1.join();
Eczema2.start();
Eczema2.join();
return Math.min (Eczema1.getAurite(), Eczema2.getAurite());
}
}
I followed the instructions of the exercise but when I chech it on the cmd the following error occurs:
Field servulate not found: java.lang.NoSuchFieldException: servulate.
Any ideas how I fix it?
You appear to be accessing a field named servulate while the proper field name is serlvulate. Find the line where this happens and fix the spelling.

Java ArrayPointStoreException and NullPointerException

This is my code. A simple demonstration of method overriding.
public class Bond {
void display() {
System.out.println("Bond");
}
}
public class ConvertibleBond extends Bond {
void display() {
System.out.println("ConvertibleBond");
}
}
public class Pg177E2 {
public static void main(String[]args) {
int random = (int)(10*Math.random());
Bond bond[] = new ConvertibleBond[6];
for(int i = 0; i < 6 ;i++) {
if(random < 5) {
bond[i] = new Bond(); // the problem occurs here
} else if(random > 5) {
bond[i] = new ConvertibleBond();
}
}
for(int i = 0; i < 6; i++) {
bond[i].display();
}
}
}
This would be simple enough and it should work; however, it is coming up as an ArrayPointStoreException and NullPointerException. Can anyone please help me out? I have no idea what I did wrong. Everything looks placed in order. The classes are all in the same package.
Bond bond[] = new ConvertibleBond[6];
bond[i] = new Bond();
You have an array of ConvertibleBond. It can only take instances of that, not any old Bond.
You probably wanted
Bond bond[] = new Bond[6];

How to use the the count number somewhere else in java

Is there anyway in which I can place count into a variable. E.g. I have Count to count the number of lines. After that I want to use the number that the count has provided, and then add this number in a variable that can be used somewhere else, e.g. to add with another number, or find an percentage or to create a pie chart using the number.
public void TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
file.close();
I want to use the number that I will get in count, and use it somewhere else (e.g another method), but I have no idea how to do that.
Thank you.
Firstly I recommend that you should complete this javatutorial if you new to programming.
If you define it in class as a global variable(as an attribute of class) out of method, you can use it in every method in your class.
But if your question about to using it in everywhere of the project within different class, you can use singleton design pattern;
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null)
{
instance = new ClassicSingleton();
}
return instance;
}
}
EDIT
Make a getter method for count variable.
E.g.
public class Test {
private int count = 0;
public void method1(){
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
}
public void method2(){
System.out.println(count);
}
public int getCount(){
return count;
}
}
Just return the value in the method you created:
public class Test {
public int TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()) {
count++;
file.nextLine();
}
System.out.println(count);
file.close();
return count;
}
public static void main(String[] args) {
Test t = new Test();
int testCount = TotalCount12();
}
}

nullPointerException I cannot figure out in Java generic class

I am trying to write program and keep getting a nullPointerException when I call a particular method, what does this mean ?
I think it should be
private int size; //non static
private static <S extends Comparable<S>> MyList<S> leftHalf(MyList<S> list) {
MyList<S> leftSide = new MyList<S>();
int middle = list.size() /2;
for (int countToMiddle = 0; countToMiddle < middle; countToMiddle++) {
leftSide.addEnd(list.head());
}
return leftSide;
}
if no, please provide more information about what this method should do.
upd:
construction issue
public MyList() { //takes no arguments
nodes = null;
}
public MyList(T... args) { //takes any number of arguments
this();
for(T t : args){
add(t);
}
}
upd:
addEnd issue
public void addEnd(T item) {
if (nodes == null) {
nodes = new NodesList<T>(item, null);
return;
}
if (nodes.tail == null) {
nodes.tail = new NodesList<T>(item, null);
} else {
nodes.tail == new NodesList<T>(nodes.tail, item);
}
}

Categories

Resources