Junit testing with random number












0















I am new to testing. I am using netbeans.



I have college assignment for junit testing but i am not so sure how should i test random number method.
My question is how should I test below method?



/**
* Method will generate a set of integers between the minimum and maximum of
* the requested size. If the uniqueElements is true the set will consist of
* unique integer values
*
* @param size the number of elements for the array
* @param minimum the lower value of the range of integers to generate
* @param maximum the upper value of the range of integers to generate
* @param uniqueElements flag for unique values
* @return
*/
public static ArrayList<Integer> createSet(int size, int minimum, int maximum, boolean uniqueElements) {
boolean filled = false;
int i = 0;
ArrayList<Integer> arraySet = null;
if (size > 0) {
arraySet = new ArrayList<Integer>();
boolean isUnique = false;
while (!filled) {
int randi = (int) (Math.random() * (maximum - minimum)) + minimum;
// C isu = true;
// C for (int j = 0; j < i && u; j++) {
// ** NEED &= isu = randi != A.get(j);
// C }
//
// if (isu || !u) {
// A.add(randi);
// i++;
// }
isUnique = true;
for (int j = 0; j < i && uniqueElements; j++) {
isUnique = randi != arraySet.get(j);
}

if (isUnique || !uniqueElements) {
arraySet.add(randi);
i++;
}

filled = (i == size);
}
}
return arraySet;
}


For this assignment professor told me that cover 100% code coverage.
I am not sure how should i Do that?



I created this test case



/**
* Test of createSet method, of class ArraySetUtilities.
*/
@Test(timeout = 5000)
public void testCreateSet() {

System.out.println("createSet");
int size = 0;
int minimum = 0;
int maximum = 0;
boolean uniqueElements = true;
ArrayList<Integer> expResult = null;
ArrayList<Integer> result = ArraySetUtilities.createSet(size, minimum, maximum, uniqueElements);
assertEquals(expResult, result);

}


Thank you in advance










share|improve this question

























  • What are your test cases? Keep in mind there are three if-statements in your method under test.

    – flopshot
    Nov 26 '18 at 1:33
















0















I am new to testing. I am using netbeans.



I have college assignment for junit testing but i am not so sure how should i test random number method.
My question is how should I test below method?



/**
* Method will generate a set of integers between the minimum and maximum of
* the requested size. If the uniqueElements is true the set will consist of
* unique integer values
*
* @param size the number of elements for the array
* @param minimum the lower value of the range of integers to generate
* @param maximum the upper value of the range of integers to generate
* @param uniqueElements flag for unique values
* @return
*/
public static ArrayList<Integer> createSet(int size, int minimum, int maximum, boolean uniqueElements) {
boolean filled = false;
int i = 0;
ArrayList<Integer> arraySet = null;
if (size > 0) {
arraySet = new ArrayList<Integer>();
boolean isUnique = false;
while (!filled) {
int randi = (int) (Math.random() * (maximum - minimum)) + minimum;
// C isu = true;
// C for (int j = 0; j < i && u; j++) {
// ** NEED &= isu = randi != A.get(j);
// C }
//
// if (isu || !u) {
// A.add(randi);
// i++;
// }
isUnique = true;
for (int j = 0; j < i && uniqueElements; j++) {
isUnique = randi != arraySet.get(j);
}

if (isUnique || !uniqueElements) {
arraySet.add(randi);
i++;
}

filled = (i == size);
}
}
return arraySet;
}


For this assignment professor told me that cover 100% code coverage.
I am not sure how should i Do that?



I created this test case



/**
* Test of createSet method, of class ArraySetUtilities.
*/
@Test(timeout = 5000)
public void testCreateSet() {

System.out.println("createSet");
int size = 0;
int minimum = 0;
int maximum = 0;
boolean uniqueElements = true;
ArrayList<Integer> expResult = null;
ArrayList<Integer> result = ArraySetUtilities.createSet(size, minimum, maximum, uniqueElements);
assertEquals(expResult, result);

}


Thank you in advance










share|improve this question

























  • What are your test cases? Keep in mind there are three if-statements in your method under test.

    – flopshot
    Nov 26 '18 at 1:33














0












0








0








I am new to testing. I am using netbeans.



I have college assignment for junit testing but i am not so sure how should i test random number method.
My question is how should I test below method?



/**
* Method will generate a set of integers between the minimum and maximum of
* the requested size. If the uniqueElements is true the set will consist of
* unique integer values
*
* @param size the number of elements for the array
* @param minimum the lower value of the range of integers to generate
* @param maximum the upper value of the range of integers to generate
* @param uniqueElements flag for unique values
* @return
*/
public static ArrayList<Integer> createSet(int size, int minimum, int maximum, boolean uniqueElements) {
boolean filled = false;
int i = 0;
ArrayList<Integer> arraySet = null;
if (size > 0) {
arraySet = new ArrayList<Integer>();
boolean isUnique = false;
while (!filled) {
int randi = (int) (Math.random() * (maximum - minimum)) + minimum;
// C isu = true;
// C for (int j = 0; j < i && u; j++) {
// ** NEED &= isu = randi != A.get(j);
// C }
//
// if (isu || !u) {
// A.add(randi);
// i++;
// }
isUnique = true;
for (int j = 0; j < i && uniqueElements; j++) {
isUnique = randi != arraySet.get(j);
}

if (isUnique || !uniqueElements) {
arraySet.add(randi);
i++;
}

filled = (i == size);
}
}
return arraySet;
}


For this assignment professor told me that cover 100% code coverage.
I am not sure how should i Do that?



I created this test case



/**
* Test of createSet method, of class ArraySetUtilities.
*/
@Test(timeout = 5000)
public void testCreateSet() {

System.out.println("createSet");
int size = 0;
int minimum = 0;
int maximum = 0;
boolean uniqueElements = true;
ArrayList<Integer> expResult = null;
ArrayList<Integer> result = ArraySetUtilities.createSet(size, minimum, maximum, uniqueElements);
assertEquals(expResult, result);

}


Thank you in advance










share|improve this question
















I am new to testing. I am using netbeans.



I have college assignment for junit testing but i am not so sure how should i test random number method.
My question is how should I test below method?



/**
* Method will generate a set of integers between the minimum and maximum of
* the requested size. If the uniqueElements is true the set will consist of
* unique integer values
*
* @param size the number of elements for the array
* @param minimum the lower value of the range of integers to generate
* @param maximum the upper value of the range of integers to generate
* @param uniqueElements flag for unique values
* @return
*/
public static ArrayList<Integer> createSet(int size, int minimum, int maximum, boolean uniqueElements) {
boolean filled = false;
int i = 0;
ArrayList<Integer> arraySet = null;
if (size > 0) {
arraySet = new ArrayList<Integer>();
boolean isUnique = false;
while (!filled) {
int randi = (int) (Math.random() * (maximum - minimum)) + minimum;
// C isu = true;
// C for (int j = 0; j < i && u; j++) {
// ** NEED &= isu = randi != A.get(j);
// C }
//
// if (isu || !u) {
// A.add(randi);
// i++;
// }
isUnique = true;
for (int j = 0; j < i && uniqueElements; j++) {
isUnique = randi != arraySet.get(j);
}

if (isUnique || !uniqueElements) {
arraySet.add(randi);
i++;
}

filled = (i == size);
}
}
return arraySet;
}


For this assignment professor told me that cover 100% code coverage.
I am not sure how should i Do that?



I created this test case



/**
* Test of createSet method, of class ArraySetUtilities.
*/
@Test(timeout = 5000)
public void testCreateSet() {

System.out.println("createSet");
int size = 0;
int minimum = 0;
int maximum = 0;
boolean uniqueElements = true;
ArrayList<Integer> expResult = null;
ArrayList<Integer> result = ArraySetUtilities.createSet(size, minimum, maximum, uniqueElements);
assertEquals(expResult, result);

}


Thank you in advance







unit-testing testing junit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 1:35







Arpit Patel

















asked Nov 26 '18 at 1:22









Arpit PatelArpit Patel

5,69943954




5,69943954













  • What are your test cases? Keep in mind there are three if-statements in your method under test.

    – flopshot
    Nov 26 '18 at 1:33



















  • What are your test cases? Keep in mind there are three if-statements in your method under test.

    – flopshot
    Nov 26 '18 at 1:33

















What are your test cases? Keep in mind there are three if-statements in your method under test.

– flopshot
Nov 26 '18 at 1:33





What are your test cases? Keep in mind there are three if-statements in your method under test.

– flopshot
Nov 26 '18 at 1:33












1 Answer
1






active

oldest

votes


















1














As @flopshot said, you should have all the IFs cover. In order to do that you have to control the random number that your test is producing.



In order to do so I would recommend you would replace the Math.random() with SingletonRandom and use mock framework such as JMockit.



Changing your "production" code in order to be testable is something that has to be considered carefully, however, mocking random is good scenario for this.



You can create interface with random method and implement it twice stack exchange question, or create a class SingletonRandom and Mock it in your test. The same concept is described here mock singleton with jmockit.



public class SingletonRandom {
private SingletonRandom() {}

public static SingletonRandom newInstance() {
return new SingletonRandom();
}

public double getRandomNumber() {
return Math.random();
}
}


In your class do something like that



int randi = (int) (SingletonRandom.newInstance().random() * (maximum - minimum)) + minimum;


And in the test Mock the SingletonRandom



ClassTest {
@Mocked
SingletonRandom SingletonRandom;

@Test
testMethod() {
new Expectations() {{
SingletonGenerator.newInstance(); result = singletonGenerator;
singletonGenerator.getRandomNumber(); result = new double { 1.2, 2.5, 3.7 }; // Add the requested "random" numbers for your if casses
}};

// Add calls to method with assertion here
}
}


You can further read about Expectations here A Guide to JMockit Expectations






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473656%2fjunit-testing-with-random-number%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    As @flopshot said, you should have all the IFs cover. In order to do that you have to control the random number that your test is producing.



    In order to do so I would recommend you would replace the Math.random() with SingletonRandom and use mock framework such as JMockit.



    Changing your "production" code in order to be testable is something that has to be considered carefully, however, mocking random is good scenario for this.



    You can create interface with random method and implement it twice stack exchange question, or create a class SingletonRandom and Mock it in your test. The same concept is described here mock singleton with jmockit.



    public class SingletonRandom {
    private SingletonRandom() {}

    public static SingletonRandom newInstance() {
    return new SingletonRandom();
    }

    public double getRandomNumber() {
    return Math.random();
    }
    }


    In your class do something like that



    int randi = (int) (SingletonRandom.newInstance().random() * (maximum - minimum)) + minimum;


    And in the test Mock the SingletonRandom



    ClassTest {
    @Mocked
    SingletonRandom SingletonRandom;

    @Test
    testMethod() {
    new Expectations() {{
    SingletonGenerator.newInstance(); result = singletonGenerator;
    singletonGenerator.getRandomNumber(); result = new double { 1.2, 2.5, 3.7 }; // Add the requested "random" numbers for your if casses
    }};

    // Add calls to method with assertion here
    }
    }


    You can further read about Expectations here A Guide to JMockit Expectations






    share|improve this answer




























      1














      As @flopshot said, you should have all the IFs cover. In order to do that you have to control the random number that your test is producing.



      In order to do so I would recommend you would replace the Math.random() with SingletonRandom and use mock framework such as JMockit.



      Changing your "production" code in order to be testable is something that has to be considered carefully, however, mocking random is good scenario for this.



      You can create interface with random method and implement it twice stack exchange question, or create a class SingletonRandom and Mock it in your test. The same concept is described here mock singleton with jmockit.



      public class SingletonRandom {
      private SingletonRandom() {}

      public static SingletonRandom newInstance() {
      return new SingletonRandom();
      }

      public double getRandomNumber() {
      return Math.random();
      }
      }


      In your class do something like that



      int randi = (int) (SingletonRandom.newInstance().random() * (maximum - minimum)) + minimum;


      And in the test Mock the SingletonRandom



      ClassTest {
      @Mocked
      SingletonRandom SingletonRandom;

      @Test
      testMethod() {
      new Expectations() {{
      SingletonGenerator.newInstance(); result = singletonGenerator;
      singletonGenerator.getRandomNumber(); result = new double { 1.2, 2.5, 3.7 }; // Add the requested "random" numbers for your if casses
      }};

      // Add calls to method with assertion here
      }
      }


      You can further read about Expectations here A Guide to JMockit Expectations






      share|improve this answer


























        1












        1








        1







        As @flopshot said, you should have all the IFs cover. In order to do that you have to control the random number that your test is producing.



        In order to do so I would recommend you would replace the Math.random() with SingletonRandom and use mock framework such as JMockit.



        Changing your "production" code in order to be testable is something that has to be considered carefully, however, mocking random is good scenario for this.



        You can create interface with random method and implement it twice stack exchange question, or create a class SingletonRandom and Mock it in your test. The same concept is described here mock singleton with jmockit.



        public class SingletonRandom {
        private SingletonRandom() {}

        public static SingletonRandom newInstance() {
        return new SingletonRandom();
        }

        public double getRandomNumber() {
        return Math.random();
        }
        }


        In your class do something like that



        int randi = (int) (SingletonRandom.newInstance().random() * (maximum - minimum)) + minimum;


        And in the test Mock the SingletonRandom



        ClassTest {
        @Mocked
        SingletonRandom SingletonRandom;

        @Test
        testMethod() {
        new Expectations() {{
        SingletonGenerator.newInstance(); result = singletonGenerator;
        singletonGenerator.getRandomNumber(); result = new double { 1.2, 2.5, 3.7 }; // Add the requested "random" numbers for your if casses
        }};

        // Add calls to method with assertion here
        }
        }


        You can further read about Expectations here A Guide to JMockit Expectations






        share|improve this answer













        As @flopshot said, you should have all the IFs cover. In order to do that you have to control the random number that your test is producing.



        In order to do so I would recommend you would replace the Math.random() with SingletonRandom and use mock framework such as JMockit.



        Changing your "production" code in order to be testable is something that has to be considered carefully, however, mocking random is good scenario for this.



        You can create interface with random method and implement it twice stack exchange question, or create a class SingletonRandom and Mock it in your test. The same concept is described here mock singleton with jmockit.



        public class SingletonRandom {
        private SingletonRandom() {}

        public static SingletonRandom newInstance() {
        return new SingletonRandom();
        }

        public double getRandomNumber() {
        return Math.random();
        }
        }


        In your class do something like that



        int randi = (int) (SingletonRandom.newInstance().random() * (maximum - minimum)) + minimum;


        And in the test Mock the SingletonRandom



        ClassTest {
        @Mocked
        SingletonRandom SingletonRandom;

        @Test
        testMethod() {
        new Expectations() {{
        SingletonGenerator.newInstance(); result = singletonGenerator;
        singletonGenerator.getRandomNumber(); result = new double { 1.2, 2.5, 3.7 }; // Add the requested "random" numbers for your if casses
        }};

        // Add calls to method with assertion here
        }
        }


        You can further read about Expectations here A Guide to JMockit Expectations







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 12:34









        Gal SGal S

        757213




        757213






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473656%2fjunit-testing-with-random-number%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)