I'm writing my spring-boot controller post request's unit tests. The post request accepts the body of type Message
class Message {
String Type,
String content
}
type can be any value from the MessageType
interface MessageType {
String PLAIN = "PLAIN";
String ACTION = "ACTION";
String NOTIFICATION = "NOTIFICATION";
.....
}
Since I want to confirm that controller accepts all supported message types I am writing the unit test for each type as shown below
@Test
void saveActivityTest_WhenTypeIsPlain() throws Exception {
CimMessage cimMessage = new CimMessage();
cimMessage.setType(MessageType.PLAIN);
cimMessage.setContent("Dummy");
mockMvc.perform(post("/activities").
contentType(MediaType.APPLICATION_JSON).
content(objectMapper.writeValueAsString(cimMessage)))
.andExpect(status().isOk());
}
As types might evolve over time and I would have to build a new unit test for every type, I was wondering if there was a general or effective way to unit test this.
I finally resort to writing a unit test for each type, which does not seem like an efficient method.
You can use "Parametrized Test"
@ParameterizedTest
@ValueSource(strings = {MessageType.PLAIN, MessageType.ACTION, MessageType.NOTIFICATION })
void saveActivityTest_WhenTypeIsPlain(String messageType) throws Exception {
CimMessage cimMessage = new CimMessage();
cimMessage.setType(messageType);
...
}
You can input parameters as single values, in CSV format, or by using a method for more complex cases. See more in https://www.baeldung.com/parameterized-tests-junit-5