Skip to content

Commit

Permalink
Simplify assertions (openhab#3996)
Browse files Browse the repository at this point in the history
* Simplify assertions

Using the appropriate assertion methods results in less and easier to read code as well as better error messages when assertions fail.

Signed-off-by: Wouter Born <github@maindrain.net>
Signed-off-by: Ciprian Pascu <contact@ciprianpascu.ro>
  • Loading branch information
wborn authored and Ciprian Pascu committed Jan 17, 2024
1 parent 76da465 commit 7bebd52
Show file tree
Hide file tree
Showing 16 changed files with 50 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public void testMultiServiceAnnotationActions() {
assertEquals(ACTION_INPUT1_DEFAULT_VALUE, in.getDefaultValue());
assertEquals(ACTION_INPUT1_DESCRIPTION, in.getDescription());
assertEquals(ACTION_INPUT1_REFERENCE, in.getReference());
assertEquals(true, in.isRequired());
assertTrue(in.isRequired());
assertEquals("Item", in.getType());

Set<String> inputTags = in.getTags();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ public void testModuleInputResolving() {
@Test
public void testSplitReferenceToTokens() {
assertNull(ReferenceResolver.splitReferenceToTokens(null));
assertTrue(ReferenceResolver.splitReferenceToTokens("").length == 0);
assertEquals(0, ReferenceResolver.splitReferenceToTokens("").length);
final String[] referenceTokens = ReferenceResolver
.splitReferenceToTokens(".module.array[\".na[m}.\"e\"][1].values1");
assertTrue("module".equals(referenceTokens[0]));
assertTrue("array".equals(referenceTokens[1]));
assertTrue(".na[m}.\"e".equals(referenceTokens[2]));
assertTrue("1".equals(referenceTokens[3]));
assertTrue("values1".equals(referenceTokens[4]));
assertEquals("module", referenceTokens[0]);
assertEquals("array", referenceTokens[1]);
assertEquals(".na[m}.\"e", referenceTokens[2]);
assertEquals("1", referenceTokens[3]);
assertEquals("values1", referenceTokens[4]);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void waitForAssertShouldRunAfterLastCallWhenAssertionSucceeds() {
public void waitForAssertShouldRunAfterLastCallWhenAssertionFails() {
Runnable afterLastCall = mock(Runnable.class);
try {
javaTest.waitForAssert(() -> assertTrue(false), null, afterLastCall, 100, 50);
javaTest.waitForAssert(() -> fail(), null, afterLastCall, 100, 50);
} catch (final AssertionError ex) {
}
verify(afterLastCall, times(1)).run();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,6 @@ public void testTokenNotExpiredEvenWithBuffer() {
// token has a life time of 60 seconds
token.setExpiresIn(60);

assertTrue(!token.isExpired(Instant.now(), 10), "Token should have been expired due to buffer");
assertFalse(token.isExpired(Instant.now(), 10), "Token should not have been expired even due to buffer");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public void simpleLRUPutAndGetTest() throws IOException {
LRUMediaCacheEntry<MetadataSample> cacheEntry = new LRUMediaCacheEntry<>("key1");
lruCache.put(cacheEntry);
assertEquals(cacheEntry, lruCache.cachedResults.get("key1"));
assertEquals(null, lruCache.cachedResults.get("key2"));
assertNull(lruCache.cachedResults.get("key2"));
}

/**
Expand Down Expand Up @@ -120,15 +120,15 @@ public void putAndGetAndEvictionOrderLRUTest() throws IOException {
lruCache.makeSpace();
// cacheEntry1 should be evicted now (size limit is 10, and effective size is 12 when we try to put the
// cacheEntry4)
assertEquals(null, lruCache.cachedResults.get("key1"));
assertNull(lruCache.cachedResults.get("key1"));

// getting cacheEntry2 will put it in head, cacheEntry3 is now tail
assertEquals(cacheEntry2, lruCache.cachedResults.get("key2"));

// putting again cacheEntry1 should expel tail, which is cacheEntry3
lruCache.cachedResults.put(cacheEntry1.getKey(), cacheEntry1);
lruCache.makeSpace();
assertEquals(null, lruCache.cachedResults.get("key3"));
assertNull(lruCache.cachedResults.get("key3"));
}

/**
Expand Down Expand Up @@ -200,7 +200,7 @@ public void putExistingResultLRUTest() throws IOException {
lruCache.makeSpace();

// key2 should be expelled now
assertEquals(null, lruCache.cachedResults.get("key2"));
assertNull(lruCache.cachedResults.get("key2"));

// key1 and key3 are a hit
assertEquals(cacheEntry, lruCache.cachedResults.get("key1"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,23 +349,23 @@ void testExpireConfig() {
cfg = new ExpireManager.ExpireConfig(testItem, "1h,15 °C", Map.of());
assertEquals(Duration.ofHours(1), cfg.duration);
assertEquals(new QuantityType<Temperature>("15 °C"), cfg.expireState);
assertEquals(null, cfg.expireCommand);
assertNull(cfg.expireCommand);

testItem = new StringItem(ITEMNAME);
cfg = new ExpireManager.ExpireConfig(testItem, "1h,NULL", Map.of());
assertEquals(Duration.ofHours(1), cfg.duration);
assertEquals(UnDefType.NULL, cfg.expireState);
assertEquals(null, cfg.expireCommand);
assertNull(cfg.expireCommand);

cfg = new ExpireManager.ExpireConfig(testItem, "1h,'NULL'", Map.of());
assertEquals(Duration.ofHours(1), cfg.duration);
assertEquals(new StringType("NULL"), cfg.expireState);
assertEquals(null, cfg.expireCommand);
assertNull(cfg.expireCommand);

cfg = new ExpireManager.ExpireConfig(testItem, "1h,'UNDEF'", Map.of());
assertEquals(Duration.ofHours(1), cfg.duration);
assertEquals(new StringType("UNDEF"), cfg.expireState);
assertEquals(null, cfg.expireCommand);
assertNull(cfg.expireCommand);
}

private Metadata config(String metadata) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.*;

import java.util.Locale;
Expand Down Expand Up @@ -88,7 +88,7 @@ public void testNoConversion(Locale locale) {
State originalState = new DecimalType(12.34);
State state = itemStateConverter.convertToAcceptedState(originalState, item);

assertTrue(originalState == state);
assertSame(originalState, state);
}

@ParameterizedTest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void testConversionToPercentType() {
@Test
public void testConversionToPointType() {
// should not be possible => null
assertEquals(null, new HSBType("100,100,100").as(PointType.class));
assertNull(new HSBType("100,100,100").as(PointType.class));
}

@Test
Expand Down Expand Up @@ -203,7 +203,7 @@ public void testCloseTo() {
assertDoesNotThrow(() -> hsb1.closeTo(hsb2, 0.1));

assertTrue(hsb1.closeTo(hsb2, 0.01));
assertTrue(!hsb1.closeTo(hsb3, 0.01));
assertFalse(hsb1.closeTo(hsb3, 0.01));
assertTrue(hsb1.closeTo(hsb3, 0.5));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public void testConstructorToString() {
// Ensure that constructor and toString are consistent
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=467612#c17
PointType point3 = PointType.valueOf("-100,200");
assertTrue(point3.equals(PointType.valueOf(point3.toString())));
assertEquals(point3, PointType.valueOf(point3.toString()));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public void testConvertionFromDimensionless() {
QuantityType<?> dt2 = QuantityType.valueOf("2");
QuantityType<?> dt3 = dt2.toUnit("m");
// Inconvertible units
assertTrue(dt3 == null);
assertNull(dt3);
}

@Test
Expand Down Expand Up @@ -343,7 +343,7 @@ public void testConversionToPercentType(Locale locale) {
new QuantityType<>(0.1, Units.RADIAN).as(PercentType.class));

// incompatible units
assertEquals(null, new QuantityType<>("0.5 m").as(PercentType.class));
assertNull(new QuantityType<>("0.5 m").as(PercentType.class));
}

@ParameterizedTest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class StringUtilsTest {
@Test
public void chompTest() {
assertEquals("", StringUtils.chomp(""));
assertEquals(null, StringUtils.chomp(null));
assertNull(StringUtils.chomp(null));
assertEquals("abc ", StringUtils.chomp("abc \r"));
assertEquals("abc", StringUtils.chomp("abc\n"));
assertEquals("abc", StringUtils.chomp("abc\r\n"));
Expand All @@ -43,7 +43,7 @@ public void chompTest() {

@Test
public void escapeXmlTest() {
assertEquals(null, StringUtils.escapeXml(null));
assertNull(StringUtils.escapeXml(null));
assertEquals(" ", StringUtils.escapeXml(" "));
assertEquals("invalidxml", StringUtils.escapeXml("invalidxml"));
assertEquals("&lt;xmlExample&gt;&amp;&lt;/xmlExample&gt;", StringUtils.escapeXml("<xmlExample>&</xmlExample>"));
Expand All @@ -55,7 +55,7 @@ public void escapeXmlTest() {

@Test
public void capitalizeTest() {
assertEquals(null, StringUtils.capitalize(null));
assertNull(StringUtils.capitalize(null));
assertEquals(" ", StringUtils.capitalize(" "));
assertEquals("Cat", StringUtils.capitalize("cat"));
assertEquals("CAt", StringUtils.capitalize("cAt"));
Expand All @@ -64,7 +64,7 @@ public void capitalizeTest() {

@Test
public void capitalizeAllWordsTest() {
assertEquals(null, StringUtils.capitalizeByUnderscore(null));
assertNull(StringUtils.capitalizeByUnderscore(null));
assertEquals("Openhab_Is_Cool", StringUtils.capitalizeByUnderscore("openHAB_is_cool"));
assertEquals("Foobar_Example", StringUtils.capitalizeByUnderscore("foobar_Example"));
assertEquals("'another_Test'", StringUtils.capitalizeByUnderscore("'another_test'"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -905,9 +905,9 @@ public void assertThatApproveAddsAllPropertiesOfDiscoveryResultToThingProperties
Thing approvedThing = inbox.approve(testThing.getUID(), testThingLabel, null);
Thing addedThing = registry.get(testThing.getUID());

assertFalse(addedThing == null);
assertFalse(approvedThing == null);
assertTrue(approvedThing.equals(addedThing));
assertNotNull(addedThing);
assertNotNull(approvedThing);
assertEquals(approvedThing, addedThing);
discoveryResultProperties.keySet().forEach(key -> {
String thingProperty = addedThing.getProperties().get(key);
String descResultParam = String.valueOf(discoveryResultProperties.get(key));
Expand Down Expand Up @@ -946,9 +946,9 @@ public void assertThatApproveSetsTheExplicitlyGivenThingId() {
Thing approvedThing = inbox.approve(testThing.getUID(), null, testId2);
Thing addedThing = registry.get(test2Thing.getUID());

assertFalse(addedThing == null);
assertFalse(approvedThing == null);
assertTrue(approvedThing.equals(addedThing));
assertNotNull(addedThing);
assertNotNull(approvedThing);
assertEquals(approvedThing, addedThing);
}

@Test
Expand Down Expand Up @@ -993,24 +993,24 @@ public Collection<ConfigDescription> getConfigDescriptions(@Nullable Locale loca

Thing approvedThing = inbox.approve(testThing.getUID(), testThingLabel, null);
Thing addedThing = registry.get(testThing.getUID());
assertTrue(approvedThing.equals(addedThing));
assertFalse(addedThing == null);
assertEquals(approvedThing, addedThing);
assertNotNull(addedThing);
for (String key : keysInConfigDescription) {
Object thingConfItem = addedThing.getConfiguration().get(key);
Object descResultParam = discoveryResultProperties.get(key);
if (descResultParam instanceof Number) {
descResultParam = new BigDecimal(descResultParam.toString());
}
assertFalse(thingConfItem == null);
assertFalse(descResultParam == null);
assertTrue(thingConfItem.equals(descResultParam));
assertNotNull(thingConfItem);
assertNotNull(descResultParam);
assertEquals(thingConfItem, descResultParam);
}
for (String key : keysNotInConfigDescription) {
String thingProperty = addedThing.getProperties().get(key);
String descResultParam = String.valueOf(discoveryResultProperties.get(key));
assertFalse(thingProperty == null);
assertFalse(descResultParam == null);
assertTrue(thingProperty.equals(descResultParam));
assertNotNull(thingProperty);
assertNotNull(descResultParam);
assertEquals(thingProperty, descResultParam);
}

services.forEach(this::unregisterService);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@ public void beforeEach() throws Exception {
public void assertThatApproveApprovesThingsWhichAreInTheInbox() {
when(inboxMock.approve(any(), any(), any())).thenReturn(testThing);

Response reponse = resource.approve(null, testThing.getUID().toString(), testThingLabel, null);
assertTrue(reponse.getStatusInfo().getStatusCode() == Status.OK.getStatusCode());
Response response = resource.approve(null, testThing.getUID().toString(), testThingLabel, null);
assertEquals(response.getStatusInfo().getStatusCode(), Status.OK.getStatusCode());
}

@Test
public void assertThatApproveDoesntApproveThingsWhichAreNotInTheInbox() {
when(inboxMock.approve(any(), any(), any())).thenThrow(new IllegalArgumentException());

Response reponse = resource.approve(null, testThing.getUID().toString(), testThingLabel, null);
assertTrue(reponse.getStatusInfo().getStatusCode() == Status.NOT_FOUND.getStatusCode());
Response response = resource.approve(null, testThing.getUID().toString(), testThingLabel, null);
assertEquals(response.getStatusInfo().getStatusCode(), Status.NOT_FOUND.getStatusCode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ public void assertItemIsBeingDisposedOnRemove() {

ArgumentCaptor<Item> itemCaptor = ArgumentCaptor.forClass(Item.class);
verify(registryChangeListener).removed(itemCaptor.capture());
assertTrue(itemCaptor.getValue() == item);
assertSame(itemCaptor.getValue(), item);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ public void testThingChannelOrder() {
resultChannels = thing.getChannels();
assertEquals(CHANNEL_IDS.size(), resultChannels.size());
for (int i = 0; i < CHANNEL_IDS.size(); i++) {
assertTrue(CHANNEL_IDS.get(i).equals(resultChannels.get(i).getUID().getId()));
assertEquals(CHANNEL_IDS.get(i), resultChannels.get(i).getUID().getId());
}

// test #2: serialize/deserialize the thing via a DTO, and compare the resulting channel order
resultChannels = ThingDTOMapper.map(ThingDTOMapper.map(thing), false).getChannels();
assertEquals(CHANNEL_IDS.size(), resultChannels.size());
for (int i = 0; i < CHANNEL_IDS.size(); i++) {
assertTrue(CHANNEL_IDS.get(i).equals(resultChannels.get(i).getUID().getId()));
assertEquals(CHANNEL_IDS.get(i), resultChannels.get(i).getUID().getId());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {
Thing thing = thingRegistry.createThingOfType(expectedThingTypeUID, expectedThingUID, expectedBridgeUID,
expectedLabel, expectedConfiguration);
waitForAssert(() -> {
assertTrue(thingResultWrapper.get() != null);
assertNotNull(thingResultWrapper.get());
});

assertThat(thing, is(notNullValue()));
Expand Down

0 comments on commit 7bebd52

Please sign in to comment.