ComeçarComece de graça

ParameterizedTest: List sum

In this exercise, you will practice providing objects as arguments for parameterized tests. Consider the sumList method and the test cases for it.

Complete the parameterized test and the arguments method.

Este exercício faz parte do curso

Introduction to Testing in Java

Ver curso

Instruções do exercício

  • Use the correct annotation for a method source and provide the method name.
  • Declare the arguments provider method, making sure it has the correct keywords and return type.
  • For the final Arguments object, use null and its expected sum.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;

import java.util.List;

import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class SumOfList {
    public static void main(String[] args) {
		launchTestsAndPrint(ListSumTest.class);
    }
}

class ListSum {
    public static int sumList(List list) {
    	if (list == null) return 0;

		int sum = 0;
        for (int element: list) {
            sum += element;
        }
        return sum;
    }
}

class ListSumTest {
    @ParameterizedTest
    // Invoke the correct annotation for a method source
    ____ 
    void sumList_sumsList(List list, int expectedSum) {
        int actualSum = ListSum.sumList(list);

        assertEquals(expectedSum, actualSum);
    }

	// Declare the correct method signature
    ____ listsAndSums() {
        return List.of(
                Arguments.of(List.of(1, 2, 3, 4), 10),
                Arguments.of(List.of(-5, 5), 0),
                Arguments.of(List.of(), 0),
                // Create a null list and the expected sum in that case
                Arguments.of(____)); 
    }
}
Editar e executar o código