Skip to content

Commit

Permalink
tried to mock mqtt, failed
Browse files Browse the repository at this point in the history
  • Loading branch information
StephanSST committed Mar 19, 2024
1 parent cdfdf30 commit 50ca8b2
Show file tree
Hide file tree
Showing 11 changed files with 163 additions and 32 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ This code will run on a Raspberry PI in a chicken barn. There are scales under t

* check logs; observer and service log twice
* log messures to file or Prometheus
* write tests and mocks for mqtt client
* implement calibrate
* write tests and mocks for mqtt client


## TODO List Arduino
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import ch.stephan.chickenfarm.registry.BoxService;

public final class MyMessageHandler {
public final class ChickenFarmMessageHandler {

public static void handleWeightMessage(String payload, BoxService boxService) {
StringTokenizer tokenizer = new StringTokenizer(payload, ";");
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/ch/stephan/chickenfarm/mqtt/MqttConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
Expand All @@ -21,6 +22,7 @@

@Slf4j
@RequiredArgsConstructor
@Profile("default")
@Configuration
public class MqttConfig {

Expand Down Expand Up @@ -70,7 +72,7 @@ MessageHandler handler() {
// if message equals (s1....
String payload = (String) message.getPayload();
log.info("Current weights: " + payload);
MyMessageHandler.handleWeightMessage(payload, boxService);
ChickenFarmMessageHandler.handleWeightMessage(payload, boxService);
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Profile("default")
@Configuration
public class MqttConfiguration {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor
@Service
public class MessagingService {
public class MqttPublisherService {
private static final String TOPIC = "/chicken-farm/commands";

@Autowired
Expand Down
12 changes: 5 additions & 7 deletions src/main/java/ch/stephan/chickenfarm/scale/ScaleService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,21 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.stephan.chickenfarm.mqtt.MessagingService;
import ch.stephan.chickenfarm.mqtt.MqttPublisherService;
import ch.stephan.chickenfarm.registry.BoxService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor
@Service
public class ScaleService {

@Autowired
private BoxService boxService;

@Autowired
private MessagingService messagingService;

public ScaleService() {
super();
}
private MqttPublisherService mqttPublisherService;

public int measureWeight(String uid) {
int weight = boxService.getBox(uid).getWeight();
Expand All @@ -33,7 +31,7 @@ public String calibrate(String uid) {
}

public String tare(String uid) {
messagingService.publish("tare:" + uid);
mqttPublisherService.publish("tare:" + uid);
log.info("Scale {} has been tared.", uid);
return "successfully tared";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import ch.stephan.chickenfarm.registry.BoxService;

@ExtendWith(MockitoExtension.class)
class MyMessageHandlerTest {
class ChickenFarmMessageHandlerTest {

@InjectMocks
private BoxService boxService;
Expand All @@ -24,7 +24,7 @@ void setUp() throws Exception {
@Test
void handleWeightMessage() {
String message = "s1:135.45;s2:-153.92";
MyMessageHandler.handleWeightMessage(message, boxService);
ChickenFarmMessageHandler.handleWeightMessage(message, boxService);
assertEquals(135, boxService.getBox("1").getWeight());
assertEquals(-153, boxService.getBox("2").getWeight());
}
Expand Down
57 changes: 57 additions & 0 deletions src/test/java/ch/stephan/chickenfarm/mqtt/MockedMqttConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package ch.stephan.chickenfarm.mqtt;

import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import ch.stephan.chickenfarm.registry.BoxService;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Configuration
@Profile({ "maven", "dev" })
public class MockedMqttConfig {

@MockBean
private BoxService boxService;

@MockBean
private MessageChannel mqttInputChannel;

@MockBean
private MqttPahoClientFactory mqttClientFactory;

@MockBean
private MessageProducer inbound;

@MockBean
private MessageHandler handler;

@Bean
MessageChannel mqttInputChannel() {
return mqttInputChannel;
}

@Bean
MqttPahoClientFactory mqttClientFactory() {
return mqttClientFactory;
}

@Bean
MessageProducer inbound() {
return inbound;
}

@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
MessageHandler handler() {
return handler;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package ch.stephan.chickenfarm.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Profile({ "maven", "dev" })
@Configuration
public class MockedMqttConfiguration {

@MockBean
private IMqttClient mqttClient;

@Bean
IMqttClient mqttClient() throws MqttException {
return mqttClient;
}

}
49 changes: 42 additions & 7 deletions src/test/java/ch/stephan/chickenfarm/scale/ScaleServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,62 @@
package ch.stephan.chickenfarm.scale;

import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

import ch.stephan.chickenfarm.mqtt.MqttPublisherService;
import ch.stephan.chickenfarm.registry.BoxService;

@ExtendWith(MockitoExtension.class)
class ScaleServiceTest {
private static final String UID = UUID.randomUUID().toString();

private static final String BOX_ID = "2";

private ScaleService scaleService;

@InjectMocks
private BoxService boxService;

@Mock
private MqttPublisherService mqttPublisherService;

@BeforeEach
void setUp() {
scaleService = new ScaleService();
MockitoAnnotations.openMocks(this);

boxService.initBoxes();

scaleService = new ScaleService(boxService, mqttPublisherService);
}

@Test
void measureWeight() {
int expectedWeight = 85;

boxService.getBox(BOX_ID).setWeight(expectedWeight);
int result = scaleService.measureWeight(BOX_ID);

assertEquals(expectedWeight, result);
}

@Test
void test() {
// when(mockedIpConnection.).thenReturn(discoveries);
void calibrate() {
String result = scaleService.calibrate(BOX_ID);

// int result = scaleService.measureWeight(UID);
assertEquals("successfully calibrated", result);
}

@Test
void tare() {
String result = scaleService.tare(BOX_ID);

// fail("Not yet implemented");
assertEquals("successfully tared", result);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import java.util.List;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -26,10 +27,11 @@
import ch.stephan.chickenfarm.dto.Measure;
import ch.stephan.chickenfarm.dto.Message;
import ch.stephan.chickenfarm.messenger.MessengerService;
import ch.stephan.chickenfarm.registry.BoxService;
import ch.stephan.chickenfarm.scale.ScaleService;

@WebMvcTest(value = MeasureController.class)
@Disabled("fix mqtt, mock it")
@Disabled("Duplicate mock definition for BoxService, reason unknown")
class MeasureControllerTest {

private static final String MESSAGE_TEXT = "Huhn hat ein Ei gelegt";
Expand All @@ -52,20 +54,31 @@ class MeasureControllerTest {
@MockBean
private MessengerService messengerService;

@MockBean
private BoxService boxService;

@BeforeEach
void setUp() {
// MockitoAnnotations.openMocks(this);
}

@Test
void testMeasure() throws Exception {
when(scaleService.measureWeight(eq(BOX1.getId()))).thenReturn(CHICKEN1.getWeight());
when(scaleService.measureWeight(eq(BOX2.getId()))).thenReturn(CHICKEN2.getWeight());
void testMeasure() throws Exception {
// when(boxService.getBoxes()).thenReturn(List.of(Box.HINTEN, Box.VORNE));

String mockMvcResult = mockMvc.perform(get("/measure").contentType(MediaType.APPLICATION_JSON))//
.andExpect(status().isOk())//
.andReturn()//
.getResponse()//
.getContentAsString();
when(scaleService.measureWeight(eq(BOX1.getId()))).thenReturn(CHICKEN1.getWeight());
when(scaleService.measureWeight(eq(BOX2.getId()))).thenReturn(CHICKEN2.getWeight());

String mockMvcResult = mockMvc.perform(get("/measure").contentType(MediaType.APPLICATION_JSON))//
.andExpect(status().isOk())//
.andReturn()//
.getResponse()//
.getContentAsString();

List<Measure> measures = objectMapper.readValue(mockMvcResult, new TypeReference<>() {});
List<Measure> measures = objectMapper.readValue(mockMvcResult, new TypeReference<>() {
});

assertNotNull(measures);
assertNotNull(measures);
assertThat(measures).hasSize(2);
assertThat(measures.get(0).boxId()).isEqualTo(BOX1.getId());
assertThat(measures.get(0).boxDescription()).isEqualTo(BOX1.getDescription());
Expand All @@ -75,7 +88,7 @@ void testMeasure() throws Exception {
assertThat(measures.get(1).boxDescription()).isEqualTo(BOX2.getDescription());
assertThat(measures.get(1).currentWeight()).isEqualTo(CHICKEN2.getWeight());
assertThat(measures.get(1).currentChicken()).isEqualTo(CHICKEN2.name());
}
}

@Test
void testSend() throws Exception {
Expand Down

0 comments on commit 50ca8b2

Please sign in to comment.