Reputation: 23
am writing a camel route test case but am getting this issue, have also included the camel route. Have debugged looks like the object is flowing through properly but on my assertion it seems to fail...
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();
}
}
(below is the camel route )
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();
Edit :
I modified the class like below by adding "mock:" to my route but is there a way to go around this? seems like it is not sending to the proper endpoint without me changing and adding the "mock:" value to where it is sending
Edit :
I added in this peice of code - to try to use adviceWith in my test class. I am calling the endpoint like so
getMockEndpoint("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT).expectedBodiesReceived(costIQPayloadString());
But am getting the error
Cannot advice routes as there are no routes
@Test
public void testReplaceFrom() throws Exception {
AdviceWith.adviceWith(context, Endpoints.SEDA_PROCESS_ENDPOINT, a -> {
a.mockEndpoints("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT);
});
}
Upvotes: 2
Views: 483
Reputation: 3697
Here is an example with route advice. Note that you probably will need to do some cleanup after your test to reset the data!
A bit older code in kotlin but should get the idea:
@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
}
}
Upvotes: 1