簡體   English   中英

編寫 apache 駱駝測試用例但出現此錯誤

[英]Writing a apache camel test case but getting this error

我正在寫一個駱駝路線測試用例,但遇到了這個問題,還包括了駱駝路線。 已調試看起來 object 正在正確流過,但根據我的斷言,它似乎失敗了......

java.lang.AssertionError: mock://seda:processMessage?blockWhenFull=true 收到的消息計數。 預期:<1> 但實際為:<0>

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.MockEndpoints;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sams.pricing.prism.data.processor.model.CostIQRetail;
import com.sams.pricing.prism.data.processor.service.RulesEngineClient;
import com.sams.pricing.prism.data.processor.util.Endpoints;



@SpringBootTest
@CamelSpringBootTest
@MockEndpoints( Endpoints.SEDA_PROCESS_ENDPOINT)
public class CamelRouteTests3  {


    

        @Autowired
        private ProducerTemplate template;

        @EndpointInject("mock:"+ Endpoints.SEDA_PROCESS_ENDPOINT)
        private MockEndpoint mock;

        @Mock
        private RulesEngineClient rulesEngineClientMock;

    
    

    public CostIQRetail costIQObject() {

        CostIQRetail obj = new CostIQRetail();

        obj.setItemNbr(123);
        obj.setLocationNbr(4931);
        obj.setIsDcFlag(false) ;
        obj.setStatus("SUCCESS");
        obj.setOrderableCost(new BigDecimal((10.0)));
        obj.setWarehousePackCost(new BigDecimal(100.0));
        obj.setOrderablePrepaidCost(null) ;
        obj.setOrderableCollectCost(null) ;
        obj.setReasonCode("Markdown - category funded");
        obj.setEffectiveDate("2022-12-29");
        obj.setIsFutureEffectiveDate(false);
        obj.setCostType("WAREHOUSE PACK COST");
        obj.setSource("COST IQ");
        obj.setCreatedBy("lab1 account");
        obj.setCreatedByUserId("LB-cost-test");
        obj.setCreatedTs("2022-12-29T02:42:25.529Z");
        obj.setCurrentRetailPrice(new BigDecimal(55.0)) ;
        obj.setCurrentOrderableCost(null);
        obj.setCurrentWarehousePackCost(new BigDecimal((0.0)));
        obj.setCurrentOrderablePrepaidCost(null) ;
        obj.setCurrentOrderableCollectCost(null);
        obj.setMarginChange(new BigDecimal((-100.0)));
        obj.setOwedToClub(new BigDecimal((0.0))); 
        obj.setItemSourceId(3572924); 
        obj.setPriceDestId(701800);
        obj.setCategory(87);
        obj.setOrderableQty(null);
        obj.setOldMargin(new BigDecimal((100.0)));
        obj.setNewMargin(new BigDecimal(0.0));  

        return obj;
    }

    private String costIQPayloadString() throws JsonProcessingException
    {

         String key =  "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":55.0,\"createdBy\":\"lab1 account\"}";
    //   String key2 = "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"categoryId\":87,\"subCategoryId\":1,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":10.0,\"createdBy\":\"lab1 account\"}";
         return key;

//      CostIQPayloadTransformer transformer = new CostIQPayloadTransformer();
//      return transformer.payloadTransformer(costIQObject());
    }


    @Test
     void test() throws Exception {
        // Set up the mock endpoints
        mock.expectedBodiesReceived(costIQPayloadString());
        
        //getMockEndpoint( mock  +  Endpoints.SEDA_PROCESS_ENDPOINT).expectedBodiesReceived(costIQPayloadString());


        //**need to properly mock and return this value
        Mockito.when(rulesEngineClientMock.validateRules((costIQObject()))).thenReturn(costIQObject());  //.thenR

        Map<String, Object> headers = new HashMap<>();
        headers.put("appName", "costIQ");

        //   Send the test message to the SEDA_SEND_ENDPOINT
        template.sendBodyAndHeaders(Endpoints.SEDA_SEND_ENDPOINT, costIQObject(), headers);

        //System.out.println("here " +mock.());
        mock.assertIsSatisfied();


    
    }



}

(以下為駱駝路線)

 ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
    ExecutorService executorService =
        MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);

    @SuppressWarnings("resource")
    ThrottlingInflightRoutePolicy throttlingInflightRoutePolicy =
        new ThrottlingInflightRoutePolicy();
    throttlingInflightRoutePolicy.setMaxInflightExchanges(150);
    throttlingInflightRoutePolicy.setResumePercentOfMax(25);

    // Camel's error handler that will attempt to redeliver the message 3 times
    errorHandler(deadLetterChannel("seda:costIqDeadLetterChannel")
                    .maximumRedeliveries(3)
                    .redeliveryDelay(3000)
    );

    // SEDA Endpoint Stage Event Driven Architecture
    from(Endpoints.SEDA_SEND_ENDPOINT)
        .messageHistory()
        // Route Name
        .routeId(Endpoints.SEDA_SEND_ENDPOINT)

        // multicast
        .multicast()
        .parallelProcessing() // create parallel threads

        // thread pool
        .threads()
        .executorService(executorService) // specific thread pool
        .log("Camel Route Started Message Processing : - ${body}")

        .choice()
        .when(PrismUtility.costIQPredicate)
        .circuitBreaker()
        .inheritErrorHandler(true)
        .bean(CostIQService.class, PrismConstants.CALCULATE_PRICE) // rules engine call
        .bean(
            CostIQPayloadTransformer.class,
            PrismConstants.PAYLOAD_TRANSFORMER) // payload transformer
        .to(
            Endpoints.SEDA_PROCESS_ENDPOINT // consumer 1
            )
        .endCircuitBreaker()
        .endChoice()

        .log("Final :- ${body}")
        .end();

編輯:

我通過在我的路線中添加“模擬:”修改了 class,如下所示,但是有沒有辦法繞過這個 go? 如果我不更改並將“模擬:”值添加到它發送的位置,它似乎沒有發送到正確的端點

編輯:

我添加了這段代碼 - 嘗試在我的測試 class 中使用 adviceWith。我這樣調用端點

    getMockEndpoint("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT).expectedBodiesReceived(costIQPayloadString());

但是我收到錯誤

無法建議路線,因為沒有路線

   @Test
    public void testReplaceFrom() throws Exception {
        AdviceWith.adviceWith(context, Endpoints.SEDA_PROCESS_ENDPOINT, a -> {
            a.mockEndpoints("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT);
        });
        }

這是一個帶有路線建議的示例。 請注意,您可能需要在測試后進行一些清理以重置數據!

kotlin 中的代碼有點舊,但應該明白了:

@SpringBootTest
class YourTest {
    @Autowired
    private lateinit var camelContext: CamelContext

    @Autowired
    private lateinit var template: ProducerTemplate

    // No MockEndpoints

    ...

    @Throws(Exception::class)
    private fun configureMockEndpoint() {
        AdviceWith.adviceWith(
            camelContext,
            "yourRouteId"
        ) { adviceWithRouteBuilder: AdviceWithRouteBuilder ->
            adviceWithRouteBuilder.replaceFromWith("direct:test")
        }
    }

    @Test
    fun yourTest() {
        configureMockEndpoint()
        template.sendBodyAndHeader("direct:test", "Your headers", """
            your content
        """.trimIndent())
        // asserts
        // cleanups
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM