Spring Boot 正在编写apache camel测试用例,但出现此错误

rsl1atfo  于 2023-01-05  发布在  Spring
关注(0)|答案(1)|浏览(157)

我正在写一个 Camel 路线测试用例,但我得到了这个问题,也包括 Camel 路线。已经调试看起来像对象是通过正确的流动,但在我的Assert,它似乎失败了...
java.lang.AssertionError: mock://seda:processMessage?blockWhenFull=true Received message count. Expected: <1> but was: <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();

    
    }


}

(下图为 Camel 路线)

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();

编辑:
我修改了类,如下所示,将"mock:"添加到我的路由中,但有没有办法绕过这个问题?如果我不更改并将"mock:"值添加到它要发送的位置,它似乎不会发送到正确的端点
编辑:
我添加了这段代码-尝试在我的测试类中使用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);
        });
        }
j2datikz

j2datikz1#

下面是一个关于路线建议的例子。注意你可能需要在测试后做一些清理工作来重置数据!
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
    }

}

相关问题