英文:
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({
"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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论