1

Spring Rest ドキュメントの使用中に発生した問題を解決してください。Springマニュアルから必要なすべての設定を行いました。Spring MVC テストを書きました。これがコードです。奇妙な記号はロシア語です。

@WebAppConfiguration
@ContextConfiguration(classes = {TestConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles({"test"})
@Slf4j
public class ProductApiControllerTest {

    protected static final long TEST_PRODUCT_ID_1 = 11_071_076_993L;
    protected static final long TEST_PRODUCT_ID_2 = 21_071_076_994L;

    public static final Product TEST_PRODUCT_1 = Product.builder()
            .id(TEST_PRODUCT_ID_1)
            .productId(TEST_PRODUCT_ID_1)
            .name("WRX3000")
            .fullName("WRX3000")
            .regionPickupAvailable(Arrays.asList("a100"))
            .regionDeliveryAvailable(Arrays.asList("b200"))
            .categoryId(100500)
            .categoryName("Телевизоры")
            .categories(Arrays.asList(10L, 20L, 30L))
            .brandId(200300)
            .brandName("Samsung")
            .description("AMOLED HD Телевизор 4 поколения")
            .prices(Arrays.asList(Price.builder().baseStore("b200").priceId(777).priceValue(2990d).oldPriceValue(3490d).build()))
            .build();

    @Mock
    private SearchService searchServiceMock;

    @InjectMocks
    private ProductApiController controller;

    private MockMvc mockMvc;
    private RestDocumentationResultHandler document;


    @Rule
    public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        this.document = document("{method-name}", preprocessResponse(prettyPrint()));
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .apply(documentationConfiguration(this.restDocumentation).snippets().withEncoding("UTF-8"))
                .alwaysDo(document)
                .build();
    }

    @Test
    public void testGetProduct() throws Exception {
        log.info("Test getProduct(..) from ProductApiController");
        when(searchServiceMock.findByProductId(TEST_PRODUCT_ID_1, "b200")).thenReturn(TEST_PRODUCT_1);
        this.document.snippets(responseFields(
                fieldWithPath("id").description("Идентификатор для служебных целей поисковой машины."),
                fieldWithPath("name").description("Название продукта"),
                fieldWithPath("fullName").description("Полное название продукта"),
                fieldWithPath("productId").description("Идентификатор (SKU) товара"),
                fieldWithPath("regionPickupAvailable").description("Показывает доступен ли продукт для самовывоза в данном регионе"),
                fieldWithPath("regionDeliveryAvailable").description("Показывает доступен ли продукт для доставки в данном регионе"),
                fieldWithPath("categoryId").description("Идентификатор категории, к которой принадлежит товар"),
                fieldWithPath("categoryName").description("Название категории, к которой принадлежит товар"),
                fieldWithPath("categories").description("Список идентификаторов категорий к которым принадлежит товар"),
                fieldWithPath("brandId").description("Идентификатор бренда товара"),
                fieldWithPath("brandName").description("Название бренда продукта"),
                fieldWithPath("description").description("Описание товара"),
                fieldWithPath("propertyAggregate").description("Какая-то фигня"),
                fieldWithPath("propepropertyAggregatertyMap").description("Дополнительные свойства товара"),
                fieldWithPath("price").description("Цена товара"),
                fieldWithPath("oldPrice").description("Предыдущая цена товара")
        ));
        mockMvc.perform(get(Constants.RestApiV1.ROOT_PATH + "/" + Constants.RestApiV1.GET_PRODUCTS + "/" + TEST_PRODUCT_ID_1 + "?baseStore=b200").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.productId").value(TEST_PRODUCT_ID_1))
                .andExpect(jsonPath("$.name").value("WRX3000"))
                .andExpect(jsonPath("$.fullName").value("WRX3000"))
                .andExpect(jsonPath("$.regionPickupAvailable").value(false)) // a100 != b200
                .andExpect(jsonPath("$.regionDeliveryAvailable").value(true)) // b200 == b200
                .andExpect(jsonPath("$.categoryId").value(100500))
                .andExpect(jsonPath("$.brandName").value("Samsung"));
    }
}

問題は、IDE (Intellij IDEA) からこのテストを開始すると、正常に動作し、すべてのスニペットが生成されることです。しかし、Maven の「パッケージ」タスク テストを実行すると、結果が表示されて失敗します。

Tests in error: 
  testGetProduct(ru.eldorado.searchservice.web.controllers.rest.ProductApiControllerTest): com.fasterxml.jackson.core.JsonParseException: Invalid UTF-8 middle byte 0xe5

問題がフィールドの説明にあることを確認しました。このパーツ パッケージのゴールを削除すると、正常に実行されます。

私のプロジェクトとすべての出力ファイルのエンコーディングは UTF-8 です。Mavenでは明示的に指定しました

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

ヘルプやアイデアをいただければ幸いです。

4

2 に答える 2

0

私自身の質問に答えます。問題はここのロシア語の文字でした

 public static final Product TEST_PRODUCT_1 = Product.builder()
            .id(TEST_PRODUCT_ID_1)
            .productId(TEST_PRODUCT_ID_1)
            .name("WRX3000")
            .fullName("WRX3000")
            .regionPickupAvailable(Arrays.asList("a100"))
            .regionDeliveryAvailable(Arrays.asList("b200"))
            .categoryId(100500)
            .categoryName("Телевизоры")
            .categories(Arrays.asList(10L, 20L, 30L))
            .brandId(200300)
            .brandName("Samsung")
            .description("AMOLED HD Телевизор 4 поколения")
            .prices(Arrays.asList(Price.builder().baseStore("b200").priceId(777).priceValue(2990d).oldPriceValue(3490d).build()))
            .build();

メソッドを追加しました

private static String getStringInUtf8(String source) {
    return new String(source.getBytes(StandardCharsets.UTF_8));
}

TEST_PRODUCT_1宣言でロシア語の文字を含む値を割り当てるために使用しました

public static final Product TEST_PRODUCT_1 = Product.builder()
        .id(TEST_PRODUCT_ID_1)
        .productId(TEST_PRODUCT_ID_1)
        .name("WRX3000")
        .fullName("WRX3000")
        .regionPickupAvailable(Arrays.asList("a100"))
        .regionDeliveryAvailable(Arrays.asList("b200"))
        .categoryId(100500)
        .categoryName(getStringInUtf8("Телевизоры"))
        .categories(Arrays.asList(10L, 20L, 30L))
        .brandId(200300)
        .brandName("Samsung")
        .description(getStringInUtf8("Super AMOLED HD Телевизор 5 поколения"))
        .prices(Arrays.asList(Price.builder().baseStore("b200").priceId(777).priceValue(2990d).oldPriceValue(3490d).build()))
        .build();

問題は解決しましたが、根本原因は見つかりませんでした。

于 2016-01-18T16:07:41.847 に答える