简体   繁体   中英

Java Constructor being called multiple times

I'm creating a PokerHand class and using JUnit tests to test it, and for some reason my constructor is called 8 times when I call it in one test method, when I create one PokerHand object.

PokerHand constructor (added a print statement to see how many times it was being called, prints 8 separate times):

//Constructor
public PokerHand (Card cardOne, Card cardTwo, Card cardThree, Card cardFour, Card cardFive) {
    System.out.println("creating hand...");
    //Initialize value array
    value = new int[6];
    //Initialize cards list, add cards, and check for duplicates
    cards = new ArrayList<Card>();

    cards.add(cardOne);
    if (cards.contains(cardTwo)) {
        throw new DuplicateCardException();
    } else cards.add(cardTwo);
    if (cards.contains(cardThree)) {
        throw new DuplicateCardException();
    } else cards.add(cardThree);
    if (cards.contains(cardFour)) {
        throw new DuplicateCardException();
    } else cards.add(cardFour);
    if (cards.contains(cardFive)) {
        throw new DuplicateCardException();
    } else cards.add(cardFive);

    determineValueOfHand();
}

Test case:

    @Test
  public void testFlush() {
      PokerHand a = new PokerHand(D10, DJ, DQ, DK, DA);
  }

I've been staring at a screen for some time and I'm new to JUnit tests and eclipse, so I'm sure I'm just missing a small detail. Any help is greatly appreciated

A hint that according to your comment fixed the problem: probably your method determineValueOfHand() erroneously creates other PokerHand objects.

In order to check for that; I recommend that

  1. your constructor
  2. your testcase

does println()s using the object reference. In addition to that, you could put entry/exit traces into your ctor! That makes it more obvious in which order constructor calls happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM