Create multiple parameter sets in one parameterized class (junit)

后端 未结 8 922
无人共我
无人共我 2021-01-30 13:05

Currently I have to create a parameterized test class for every method that I want to test with several different inputs. Is there a way to add this together in one file?

<
8条回答
  •  有刺的猬
    2021-01-30 13:22

    I use junitparams, which permits me to pass distinct set of params in each tests. JunitParams uses methods to return set of params, and in the test, you provide the method names as source of param input, so changing the method name will change data set.

    import com.xx.xx.xx.Transaction;
    import junitparams.JUnitParamsRunner;
    import junitparams.Parameters;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Set;
    
    import static org.junit.Assert.assertFalse;
    import static org.junit.Assert.assertTrue;
    
    
    @RunWith(JUnitParamsRunner.class)
    public class IpAddressValidatorTest {
    
        private Validator validator;
    
        @Before
        public void setUp() {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            validator = factory.getValidator();
    
        }
    
        public static List goodData() {
            return Arrays.asList(
                    "10.10.10.10",
                    "127.0.0.1",
                    "10.136.182.1",
                    "192.168.1.1",
                    "192.168.1.1",
                    "1.1.1.1",
                    "0.0.0.0"
            );
        }
    
        public static List badData() {
            return Arrays.asList(
                    "01.01.01.01",
                    "255.255.255.256",
                    "127.1",
                    "192.168.0.0"
            );
        }
    
        @Test
        @Parameters(method = "goodData")
        public void ipAddressShouldBeValidated_AndIsValid(String ipAddress) {
            Transaction transaction = new Transaction();
            transaction.setIpAddress(ipAddress);
            Set> violations = validator.validateProperty(transaction, "ipAddress");
            assertTrue(violations.isEmpty());
        }
    
        @Test
        @Parameters(method = "badData")
        public void ipAddressShouldBeValidated_AndIsNotValid(String ipAddress) {
            Transaction transaction = new Transaction();
            transaction.setIpAddress(ipAddress);
            Set> violations = validator.validateProperty(transaction, "ipAddress");
            assertFalse(violations.isEmpty());
        }
    
    
    }
    

提交回复
热议问题