如何在JUNIT方法中针对使用字符串和数组总和的IF语句编写测试

问题描述

我需要测试BasketBallGame类,我编写了多个可以工作的测试,现在我想在该方法中测试最终的IF语句:public BasketResult play(String category){}

我已经为其他两个IF语句编写了测试,并使用Mockito模拟ShotAttempt方法。

@ParameterizedTest
    @CsvSource({ "0,1,0","1,1","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);
        });
        
    }

现在,我不确定如何使用数组值和字符串类别的总和来测试最后的IF语句并返回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);
    }
}

解决方法

请注意@InjectMocks@Mock
另外,语句initMocks是必需的。

@InjectMocks
BasketBallGame basketBallGame;

@Mock
private InHoop inHoop;

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

@ParameterizedTest
@CsvSource({
        "toddler,'0,0',false","toddler,'1,true",1,"lower,1',})
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());
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...