如何编写一个使用String和数组总和的IF语句的测试方法,使用JUNIT。

huangapple go评论70阅读模式
英文:

How can I write a test for an IF statement that uses a String and the sum of an Array in a method with JUNIT

问题

I need to test the BasketBallGame class, ive written multiple tests who work and now I want to test the final IF statement in the method: public BasketResult play(String category) {}

I have written test for the other two IF statements and used Mockito to mock the ShotAttempt method.

@ParameterizedTest
@CsvSource({ "0, 1,0", "1,1,1", "0, 0,1" })
public void MockShotAttempt(int firstValue, int secondValue, int derdeWaarde) {
    Mockito.when(inHoop.ShotAttempt(3)).thenReturn(new int[] {firstValue,secondValue,derdeWaarde});			
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"        ", "TodDDleR", "LoWWeR","#!|@&" })
public void Invalid_EmptyCategory(String category) {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
        BasketBallGame.Play(category);
    });
}

Now i'm not really sure how I can use the sum of the array value, and the string category in order to test the last IF statement and return a BasketResult.

英文:

I need to test the BasketBallGame class, ive written multiple tests who work and now I want to test the final IF statement in the method: public BasketResult play(String category) {}

I have written test for the other two IF statements and used Mockito to mock the ShotAttempt method.

@ParameterizedTest
	@CsvSource({ "0, 1,0", "1,1,1", "0, 0,1" })
	public void MockShotAttempt(int firstValue, int secondValue, int derdeWaarde) {
		Mockito.when(inHoop.ShotAttempt(3)).thenReturn(new int[] {firstValue,secondValue,derdeWaarde});			
	}

	@ParameterizedTest
	@NullAndEmptySource
	@ValueSource(strings = {"        ", "TodDDleR", "LoWWeR","#!|@" })
	public void Invalid_EmptyCategory(String category) {
		Assertions.assertThrows(IllegalArgumentException.class, () -> {
			BasketBallGame.Play(category);
		});
		
	}

Now i'm not really sure how I can use the sum of the array value, and the string category in order to test the last IF statement and return a BasketResult.


public class BasketResult {

	private final boolean won;
	private final int amountInHoop;

	BasketResultaat(boolean won, int amountInHoop) {
		this.won = won;
		this.amountInHoop = amountInHoop;
	}

	public boolean isWon() {
		return won;
	}

	public int getAmountInHoop() {
		return amountInHoop;
	}

}

import java.security.SecureRandom;

public class InHoop {

	private final SecureRandom random = new SecureRandom();

	public int[] shotAttempt(int amountAttempts) {
		int[] score = new int[amountAttempts];
		for (int index = 0; index < amountAttempts; index++) {
			score[index] = random.nextInt(2); // 1 = in hoop, 0 = not in hoop
		}
		return score;
	}

}
import java.util.Arrays;

public class BasketBallGame {
	private InHoop inHoop;
	private final int AMOUNT_TRIES = 3;
	private final String TODDLER = "toddler";
	private final String LOWER = "lower";

	public BasketBallGame() {
		this(new InHoop());
	}

	public BasketBallGame(InHoop inHoop) {
		this.inHoop = inHoop;
	}

	public double Calculate(int x, double y) {
		if (x <= 0 || y < 0)
			throw new IllegalArgumentException("x must be stricly positive and y must be positive");
		return (AMOUNT_TRIES * 10) - x - y;
	}

	public BasketResult play(String category) {
		if (category == null || category.isBlank()) {
			throw new IllegalArgumentException("category must be filled in");
		}

		if (!categorie.equalsIgnoreCase(TODDLER) && !categorie.equalsIgnoreCase(LOWER)) {
			throw new IllegalArgumentException("INVALID category");
		}
		int[] result = inHoop.shotAttempt(AMOUNT_TRIES);

		int amountInHoop = Arrays.stream(result).sum();
		// IF toddler And 1x in hoop ==> WIN 
      	// IF LOWER AND 2X IN HOOP ==> WIN
		if ((category.equals(TODDLER) && amountInHoop >= 1)
				|| (categorie.equals(LOWER) && amountInHoop >= 2)) {
			return new BasketResult(true, amountInHoop);
		}

		// did not win 
		return new BasketResult(false, amountInHoop);
	}
}


</details>


# 答案1
**得分**: 1

Pay attention to `@InjectMocks` and `@Mock`.  
In addition, the statement `initMocks` is necessary.

```java
@InjectMocks
BasketBallGame basketBallGame;

@Mock
private InHoop inHoop;

@BeforeEach
void before() {
    MockitoAnnotations.initMocks(this);
}

@ParameterizedTest
@CsvSource({
        "toddler, '0,0,0', false",
        "toddler, '1,0,0', true",
        "toddler, '1,1,0', true",
        "lower,   '1,0,0', false",
        "lower,   '1,1,0', true",
        "lower,   '1,1,1', true",
})
public void TestLastIfStatement(String category, String scoreList, Boolean winExp) {
    int[] scoreArr = Arrays.stream(scoreList.split(",")).map(String::trim).mapToInt(Integer::parseInt).toArray();
    int sumExp = Arrays.stream(scoreArr).sum();

    when(inHoop.shotAttempt(anyInt())).thenReturn(scoreArr);

    BasketResult result = basketBallGame.play(category);

    assertEquals(winExp, result.isWon());
    assertEquals(sumExp, result.getAmountInHoop());
}
英文:

Pay attention to @InjectMocks and @Mock.
In addition, the statement initMocks is necessary.

@InjectMocks
BasketBallGame basketBallGame;

@Mock
private InHoop inHoop;

@BeforeEach
void before() {
    MockitoAnnotations.initMocks(this);
}

@ParameterizedTest
@CsvSource({
        &quot;toddler, &#39;0,0,0&#39;, false&quot;,
        &quot;toddler, &#39;1,0,0&#39;, true&quot;,
        &quot;toddler, &#39;1,1,0&#39;, true&quot;,
        &quot;lower,   &#39;1,0,0&#39;, false&quot;,
        &quot;lower,   &#39;1,1,0&#39;, true&quot;,
        &quot;lower,   &#39;1,1,1&#39;, true&quot;,
})
public void TestLastIfStatement(String category, String scoreList, Boolean winExp) {
    int[] scoreArr = Arrays.stream(scoreList.split(&quot;,&quot;)).map(String::trim).mapToInt(Integer::parseInt).toArray();
    int sumExp = Arrays.stream(scoreArr).sum();

    when(inHoop.shotAttempt(anyInt())).thenReturn(scoreArr);

    BasketResult result = basketBallGame.play(category);

    assertEquals(winExp, result.isWon());
    assertEquals(sumExp, result.getAmountInHoop());
}

huangapple
  • 本文由 发表于 2020年8月11日 03:11:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63346570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定