1

我有一个类Article有一个eanorg.hibernate.validator.constraints.EAN.

如何生成有效的 ean13 值以对一堆Articles 进行单元测试?

4

2 回答 2

2

请在下面找到一个测试有效/无效 EAN 代码的示例:

以下站点用于获取有效的 EAN 13 代码:http ://www.gomaro.ch/lecheck.htm

也许您也会对 Barcode4j API 感兴趣(例如):http ://barcode4j.sourceforge.net/

package ean;

import static org.junit.Assert.assertTrue;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.constraints.EAN;
import org.junit.Before;
import org.junit.Test;

/**
 * Test EAN 13 constraint. EAN 13 = 12 digits + 1 check digit.
 *
 */
public class testEAN13 {

    private static Validator validator;

    @BeforeClass
    public static void setUp() {
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        validator = vf.getValidator();
    }

    @Test
    public void validEAN() {
        Article product = new Article("7894561330231");
        Set<ConstraintViolation<Article>> violations = validator.validate(product);
        assertTrue(violations.isEmpty());
    }

    @Test
    public void invalidEAN() {
        Article product = new Article("7894561330235");
        Set<ConstraintViolation<Article>> violations = validator.validate(product);
        assertTrue(violations.size() == 1);
    }

    class Article {

        @EAN
        private final String ean;

        private Article(String ean) {
            this.ean = ean;
        }
    }
}

Maven 所需的依赖项:

<dependencies>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.2.Final</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.0</version>
        <scope>test</scope>
    </dependency>

</dependencies>

注意:Hibernate Validator 需要表达式语言依赖项。

于 2015-10-31T22:34:38.887 回答
0

好的,我在互联网上进行了一些研究后创建了一个 EAN13 生成器

public class EANGenerator {

    private static long _12_DIGITS = 100000000000L;

    private EANGenerator() {
    }

    /**
     * Generate the next EAN13 code
     *
     * @return
     */
    public static String getEAN13() {
        final String eanWithoutDigit = Long.toString(_12_DIGITS++);
        assertThat(eanWithoutDigit, length(equalTo(12)));

        int sum = 0;
        for (int i = 0; i < eanWithoutDigit.length(); i++) {
            sum = sum + (Integer.parseInt(String.valueOf(eanWithoutDigit.charAt(i))) * (i % 2 == 0 ? 1 : 3));
        }
        int checkDigit = sum % 10 == 0 ? 0 : (10-(sum % 10));
        return eanWithoutDigit + checkDigit;
    }

}

只需从此帮助类调用静态方法即可获得下一个 EAN13。显然,由于要检查的位数(从 12 到 13)而多次调用它会抛出异常

于 2015-11-01T10:24:02.100 回答