随机bean初始化的bean集合大小与配置的大小不匹配

时间:2018-09-25 14:25:33

标签: java spring testing random-beans

我正在尝试使用random-beans库更快地创建我的测试bean。使用的依赖项是({https://github.com/benas/random-beans):

 <dependency>
        <groupId>io.github.benas</groupId>
        <artifactId>random-beans</artifactId>
        <version>3.7.0</version>
        <scope>test</scope>
</dependency>

豆是:

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

private String  surname;

private Integer age;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;

@Entity
public class Book {


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String title;

private String description;

private Integer pages; 

这是我的测试代码(将collectionsize限制为1):

https://github.com/cristianprofile/create-test-random-beans/blob/master/src/test/java/com/cromero/randombeaninstantationtesting/RandomBeanInstantationTestingApplicationTests.java#L41

 EnhancedRandom random = EnhancedRandomBuilder.aNewEnhancedRandomBuilder()
            .charset(forName("UTF-8"))
            .stringLengthRange(5, 50)
            .collectionSizeRange(1, 1)
            .scanClasspathForConcreteTypes(true)
            .overrideDefaultInitialization(false)
            .build();
    User user = random.random(User.class);

    assertThat(user.getBooks()).hasSize(1);

我的测试在此断言中失败:

  assertThat(user.getBooks()).hasSize(1);

为什么书籍大小与我为随机对象配置的书籍大小不同。为什么会这样?

1 个答案:

答案 0 :(得分:1)

您正在非静态random实例上调用静态方法random,而应该调用nextObject方法:

User user = random.nextObject(User.class);

由于方法EnhancedRandom.random是静态的,因此它仅采用默认配置选项,而不采用在EnhancedRandom实例上设置的选项。

希望这会有所帮助。