Java Junit4 testing; protected methods -


i'm working test chunk of code - it's class called mazebuilder. problem of methods protected, can't access them in tests...

so thought test should focus on run(), accesses lot of other methods. i'm concerned impossible sort of cohesive testing done operating 1 method.

additionally, proper way test 2 constructors ( mazebuilder() , mazebuilder(boolean deterministic) )? stands, i'm testing object formed not null - i.e. they're being built @ all. there more expansive way of testing constructor i'm unaware of?

package falstad;  public class mazebuilder implements runnable {     // given input information:      protected int width, height ;   // width , height of maze,      maze maze;              // reference maze constructed, results returned calling maze.newmaze(..)     private int rooms;      // requested number of rooms in maze, room area no walls larger single cell     int expectedpartiters;  // user given limit partiters      // produced output information create new maze     // root, cells, dists, startx, starty     protected int startx, starty ; // starting position inside maze entity search exit     // conventional encoding of maze 2 dimensional integer array encapsulated in cells class     // single integer entry can hold information on walls, borders/bounds     protected cells cells; // internal representation of maze matrix of cells     protected distance dists ; // distance matrix stores how far each position away exit positino      // class internal local variables     protected singlerandom random ; // random number stream, used make randomized decisions, e.g direction go      thread buildthread; // computations performed in own separated thread this.run()      //int colchange; // randomly selected in run method of thread, used parameter segment class constructor      /**      * constructor randomized maze generation      */     public mazebuilder(){         random = singlerandom.getrandom();     }     /**      * constructor option make maze generation deterministic or random      */     public mazebuilder(boolean deterministic){         if (true == deterministic)         {             system.out.println("project 2: functionality make maze generation deterministic not implemented yet! fix this!");             // control random number generation             // todo: implement code makes sure if mazebuilder.build called same skill level twice, same results             // hint: check http://download.oracle.com/javase/6/docs/api/java/util/random.html , file singlerandom.java          }         random = singlerandom.getrandom();     }      /**      * provides sign of given integer number      * @param num      * @return -1 if num < 0, 0 if num == 0, 1 if num > 0      */     static int getsign(int num) {         return (num < 0) ? -1 : (num > 0) ? 1 : 0;     }      /**      * method generates maze.      * computes distances, determines start , exit position far apart possible.       */     protected void generate() {         // generate paths in cells such there 1 connected component         // i.e. between 2 cells in maze there path 1 other         // search algorithm starts @ random point         generatepathways();           final int[] remote = dists.computedistances(cells) ;          // identify cell greatest distance         final int[] pos = dists.getstartposition();         startx = pos[0] ;         starty = pos[1] ;          // make exit position @ true exit in cells data structure         setexitposition(remote[0], remote[1]);     }      /**      * method generates pathways maze.      *       */     protected void generatepathways() {         int[][] origdirs = new int[width][height] ;           int x = random.nextintwithininterval(0, width-1) ;         int y = 0;          final int firstx = x ;          final int firsty = y ;         int dir = 0;                 int origdir = dir;           cells.setvisitedflagtozero(x, y);          while (true) {                    int dx = constants.dirs_x[dir];             int dy = constants.dirs_y[dir];              if (!cells.cango(x, y, dx, dy)) {                   dir = (dir+1) & 3;                  if (origdir == dir) {                       if (x == firstx && y == firsty)                         break;                        int odr = origdirs[x][y];                     dx = constants.dirs_x[odr];                     dy = constants.dirs_y[odr];                      x -= dx;                     y -= dy;                        origdir = dir = random.nextintwithininterval(0, 3);                 }             } else {                   cells.deletewall(x, y, dx, dy);                  x += dx;                 y += dy;                  cells.setvisitedflagtozero(x, y);                  origdirs[x][y] = dir;                 origdir = dir = random.nextintwithininterval(0, 3);             }         }     }     /**      * establish valid exit position breaking down wall outside area.      * @param remotex      * @param remotey      */     protected void setexitposition(int remotex, int remotey) {         int bit = 0;         if (remotex == 0)             bit = constants.cw_left;         else if (remotex == width-1)             bit = constants.cw_right;         else if (remotey == 0)             bit = constants.cw_top;         else if (remotey == height-1)             bit = constants.cw_bot;         else             dbg("generate 1");         cells.setbittozero(remotex, remotey, bit);         //system.out.println("exit position set zero: " + remotex + " " + remotey + " " + bit + ":" + cells.hasmaskedbitsfalse(remotex, remotey, bit)         //      + ", corner case: " + ((0 == remotex && 0 == remotey) || (0 == remotex &&  height-1 == remotey) || (width-1 == remotex && 0 == remotey) || (width-1 == remotex && height-1 == remotey)));     }       static final int min_room_dimension = 3 ;     static final int max_room_dimension = 8 ;     /**      * allocates space room of random dimensions in maze.      * position of room chosen randomly. method not sophisticated       * such attempt may fail if maze has ample space accommodate       * room of chosen size.       * @return true if room placed, false otherwise      */     private boolean placeroom() {         // width , height of random size not large         // if large return failed attempt         final int rw = random.nextintwithininterval(min_room_dimension, max_room_dimension);         if (rw >= width-4)             return false;          final int rh = random.nextintwithininterval(min_room_dimension, max_room_dimension);         if (rh >= height-4)             return false;          // proceed given width , height         // obtain random position (rx,ry) such room located on rectangle (rx,ry) , (rxl,ryl) corner points         // upper bound chosen such width , height of room fits maze area.         final int rx = random.nextintwithininterval(1, width-rw-1);         final int ry = random.nextintwithininterval(1, height-rh-1);         final int rxl = rx+rw-1;         final int ryl = ry+rh-1;         // check cells in area if belong room         // if case, return false failed attempt         if (cells.areaoverlapswithroom(rx, ry, rxl, ryl))             return false ;         // since area available, mark room , remove walls         // on clear can place room on maze         cells.markareaasroom(rw, rh, rx, ry, rxl, ryl);          return true;     }      static void dbg(string str) {         system.out.println("mazebuilder: "+str);     }        /**      * fill given maze object newly computed maze according parameter settings      * @param mz maze filled      * @param w width of requested maze      * @param h height of requested maze      * @param roomct number of rooms      * @param pc number of expected partiters      */     public void build(maze mz, int w, int h, int roomct, int pc) {         init(mz, w, h, roomct, pc);         buildthread = new thread(this);         buildthread.start();     }      /**      * initialize internal attributes, method called build() when input parameters provided      * @param mz maze filled      * @param w width of requested maze      * @param h height of requested maze      * @param roomct number of rooms      * @param pc number of expected partiters      */     private void init(maze mz, int w, int h, int roomct, int pc) {         // store parameters         maze = mz;         width = w;         height = h;         rooms = roomct;         expectedpartiters = pc;         // initialize data structures         cells = new cells(w,h) ;         dists = new distance(w,h) ;         //colchange = random.nextintwithininterval(0, 255); // used in constructor segments  class seg     }      static final long sleep_interval = 100 ; //unit millisecond     /**      * main method run construction of new maze mazebuilder in thread of own.      * method called internally build method when sets , starts new thread object.      */     public void run() {         // try-catch block recognize if thread interrupted         try {             // create initial invalid maze walls , borders             cells.initialize();             // place rooms in maze             generaterooms();              thread.sleep(sleep_interval) ; // test if thread has been interrupted, i.e. notified stop              // put pathways maze, determine starting , end position , calculate distances             generate();              thread.sleep(sleep_interval) ; // test if thread has been interrupted, i.e. notified stop              final int colchange = random.nextintwithininterval(0, 255); // used in constructor segments  class seg             final bspbuilder b = new bspbuilder(maze, dists, cells, width, height, colchange, expectedpartiters) ;             bspnode root = b.generatebspnodes();              thread.sleep(sleep_interval) ; // test if thread has been interrupted, i.e. notified stop              // dbg("partiters = "+partiters);             // communicate results maze object             maze.newmaze(root, cells, dists, startx, starty);         }         catch (interruptedexception ex) {             // necessary catch exception avoid escalation             // exception mechanism used exit method in controlled way             // no need clean internal data structures             // dbg("catching signal stop") ;         }     }      static final int max_tries = 250 ;      /**      * generate rooms in given maze walls up. rooms placed randomly , of random sizes      * such maze can turn out small accommodate requested number of rooms (class attribute rooms).       * in case less rooms produced.      * @return generated number of rooms      */     private int generaterooms() {         // rooms randomly positioned such may impossible place rooms if maze small         // prevent infinite loop limit number of failed max_tries == 250         int tries = 0 ;         int result = 0 ;         while (tries < max_tries && result <= rooms) {             if (placeroom())                 result++ ;             else                 tries++ ;         }         return result ;     }      /**      * notify maze builder thread stop creation of maze , terminate      */     public void interrupt() {         buildthread.interrupt() ;     }    } 

to unit test protected methods, put test class in same package class looking test (in case falsted). because in same package, doesn't mean have in same directory (just parallel test directory hierarchy).

test constructors probing state of object ensure values got default or initial value.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -