Как проверить JSON API, когда коллекция установлена - PullRequest
0 голосов
/ 21 января 2019

Я прочитал, что предпочтительнее использовать Set вместо List в Hibernate.

Я создал две сущности по отношению к одной ко многим:

@Entity
public class Product {

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

    @Column(nullable = false, unique = true)
    private String name;

    @ManyToOne
    @JoinColumn(name = "company_id", nullable = false)
    private Company company;
}

@Entity
public class Company {

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

    @Column(nullable = false, unique = true)
    private String name;

    @LazyCollection(LazyCollectionOption.TRUE)
    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
    private Set<Product> products;
}

В отношении @OneToMany установить коллекцию private Установить продукты;

Затем я пытаюсь проверить результат возврата:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class CompanyControllerTest {

    private static final String API_COMPANY = "/api/company/";

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
    }

    @Test
    public void getById() throws Exception {
        int id = 1;

        this.mockMvc.perform(get(API_COMPANY + id))
                .andExpect(status().isOk())
                .andExpect(content().contentType(APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("id", is(1)))
                .andExpect(jsonPath("$.name", is("Google")))
                .andExpect(jsonPath("$.products", hasSize(2)))
                .andExpect(jsonPath("$.products[0].id", is(1)))
                .andExpect(jsonPath("$.products[0].name", is("search engine")))
                .andExpect(jsonPath("$.products[0].company").doesNotExist())
                .andExpect(jsonPath("$.products[1].id", is(2)))
                .andExpect(jsonPath("$.products[1].name", is("adv.")))
                .andExpect(jsonPath("$.products[1].company").doesNotExist());
    }
}

Но проблема в том, что список товаров постоянно меняется, потому что я использую Набор. И оказывается, что тест либо проходит, либо не проходит, так как порядок продуктов меняется.

У меня вопрос, как проверить результат при использовании Set.

1 Ответ

0 голосов
/ 21 января 2019

Вы можете получить все элементы с помощью [*] и дать Matchers.containsInAnyOrder (T ...) всех элементов, которые вы хотите проверить.

Примерно так:

 this.mockMvc.perform(get(API_COMPANY + id))
            .andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("id", is(1)))
            .andExpect(jsonPath("$.name", is("Google")))
            .andExpect(jsonPath("$.products", hasSize(2)))
            .andExpect(jsonPath("$.products[*].id", Matchers.containsInAnyOrder(1, 2)))
            .andExpect(jsonPath("$.products[*].name", Matchers.containsInAnyOrder("search engine", "adv.")))
            .andExpect(jsonPath("$.products[*].company").doesNotExist());
...