Migrate to JUnit 5 (#1580)

* Migrates all tests to the JUnit 5 Jupiter API
* Updates bnd to 5.1.2
* Updates maven-surefire-plugin to 3.0.0-M5
* Updates Mockito to 3.4.6
* Updates Hamcrest to 2.2
* Removes org.openhab.core.boot POM dependencies

Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2020-08-09 14:36:46 +02:00 committed by GitHub
parent 32a819de92
commit d3ea6063c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
306 changed files with 3308 additions and 2607 deletions

View File

@ -16,9 +16,19 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.osgi</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>osgi.enroute.junit.wrapper</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<version>4.12.0</version> <version>5.6.2</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>biz.aQute.bnd</groupId>
<artifactId>biz.aQute.tester.junit-platform</artifactId>
<version>5.1.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openhab.core.bom</groupId> <groupId>org.openhab.core.bom</groupId>

View File

@ -17,19 +17,29 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.hamcrest</groupId>
<artifactId>junit</artifactId> <artifactId>hamcrest-library</artifactId>
<version>4.12</version> <version>2.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.osgi</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>osgi.enroute.hamcrest.wrapper</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>1.3.0</version> <version>5.6.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.6.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
<version>3.1.0</version> <version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.4.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>

View File

@ -12,8 +12,7 @@
*/ */
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -22,9 +21,13 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
import org.openhab.core.audio.AudioStream; import org.openhab.core.audio.AudioStream;
import org.openhab.core.audio.ByteArrayAudioStream; import org.openhab.core.audio.ByteArrayAudioStream;
@ -40,6 +43,8 @@ import org.osgi.service.http.HttpService;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public abstract class AbstractAudioServletTest extends JavaTest { public abstract class AbstractAudioServletTest extends JavaTest {
protected AudioServlet audioServlet; protected AudioServlet audioServlet;
@ -57,10 +62,8 @@ public abstract class AbstractAudioServletTest extends JavaTest {
private @Mock HttpService httpServiceMock; private @Mock HttpService httpServiceMock;
private @Mock HttpContext httpContextMock; private @Mock HttpContext httpContextMock;
@Before @BeforeEach
public void setupServerAndClient() { public void setupServerAndClient() {
initMocks(this);
audioServlet = new AudioServlet(httpServiceMock, httpContextMock); audioServlet = new AudioServlet(httpServiceMock, httpContextMock);
ServletHolder servletHolder = new ServletHolder(audioServlet); ServletHolder servletHolder = new ServletHolder(audioServlet);
@ -72,7 +75,7 @@ public abstract class AbstractAudioServletTest extends JavaTest {
httpClient = new HttpClient(); httpClient = new HttpClient();
} }
@After @AfterEach
public void tearDownServerAndClient() throws Exception { public void tearDownServerAndClient() throws Exception {
server.stopServer(); server.stopServer();
httpClient.stop(); httpClient.stop();

View File

@ -13,16 +13,16 @@
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioException; import org.openhab.core.audio.AudioException;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
import org.openhab.core.audio.AudioSource; import org.openhab.core.audio.AudioSource;
@ -73,7 +73,7 @@ public class AudioConsoleTest extends AbstractAudioServletTest {
private final int testTimeout = 1; private final int testTimeout = 1;
@Before @BeforeEach
public void setUp() throws IOException { public void setUp() throws IOException {
fileHandler = new BundledSoundFileHandler(); fileHandler = new BundledSoundFileHandler();
audioSink = new AudioSinkFake(); audioSink = new AudioSinkFake();
@ -87,7 +87,7 @@ public class AudioConsoleTest extends AbstractAudioServletTest {
audioConsoleCommandExtension = new AudioConsoleCommandExtension(audioManager, localeProvider); audioConsoleCommandExtension = new AudioConsoleCommandExtension(audioManager, localeProvider);
} }
@After @AfterEach
public void tearDown() { public void tearDown() {
fileHandler.close(); fileHandler.close();
} }

View File

@ -13,12 +13,12 @@
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
/** /**

View File

@ -13,10 +13,10 @@
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
import org.openhab.core.audio.AudioStream; import org.openhab.core.audio.AudioStream;
import org.openhab.core.audio.ByteArrayAudioStream; import org.openhab.core.audio.ByteArrayAudioStream;
@ -37,7 +37,7 @@ public class AudioManagerServletTest extends AbstractAudioServletTest {
private AudioSinkFake audioSink; private AudioSinkFake audioSink;
@Before @BeforeEach
public void setup() { public void setup() {
audioManager = new AudioManagerImpl(); audioManager = new AudioManagerImpl();
audioSink = new AudioSinkFake(); audioSink = new AudioSinkFake();

View File

@ -13,7 +13,8 @@
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -25,9 +26,9 @@ import java.util.Collections;
import java.util.Locale; import java.util.Locale;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioException; import org.openhab.core.audio.AudioException;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
import org.openhab.core.audio.AudioSource; import org.openhab.core.audio.AudioSource;
@ -57,7 +58,7 @@ public class AudioManagerTest {
private AudioSinkFake audioSink; private AudioSinkFake audioSink;
private AudioSource audioSource; private AudioSource audioSource;
@Before @BeforeEach
public void setup() throws IOException { public void setup() throws IOException {
fileHandler = new BundledSoundFileHandler(); fileHandler = new BundledSoundFileHandler();
audioManager = new AudioManagerImpl(); audioManager = new AudioManagerImpl();
@ -68,7 +69,7 @@ public class AudioManagerTest {
when(audioSource.getLabel(any(Locale.class))).thenReturn("audioSourceLabel"); when(audioSource.getLabel(any(Locale.class))).thenReturn("audioSourceLabel");
} }
@After @AfterEach
public void tearDown() throws IOException { public void tearDown() throws IOException {
fileHandler.close(); fileHandler.close();
} }

View File

@ -12,8 +12,8 @@
*/ */
package org.openhab.core.audio.internal; package org.openhab.core.audio.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import java.io.File; import java.io.File;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -21,7 +21,7 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioFormat; import org.openhab.core.audio.AudioFormat;
import org.openhab.core.audio.AudioStream; import org.openhab.core.audio.AudioStream;
import org.openhab.core.audio.FileAudioStream; import org.openhab.core.audio.FileAudioStream;

View File

@ -12,10 +12,11 @@
*/ */
package org.openhab.core.automation.internal; package org.openhab.core.automation.internal;
import static org.junit.jupiter.api.Assertions.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
/** /**
* @author Ana Dimova - Initial contribution * @author Ana Dimova - Initial contribution
@ -24,91 +25,89 @@ public class ConnectionValidatorTest {
@Test @Test
public void testValidConnections() { public void testValidConnections() {
Assert.assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name")); assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name}")); assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name}"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "moduleId.outputName")); assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "moduleId.outputName"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1].name.values")); assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1].name.values"));
Assert.assertTrue( assertTrue(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module1.map[\"na[m}.\"e\"][1].values_1-2"));
Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module1.map[\"na[m}.\"e\"][1].values_1-2"));
} }
@Test @Test
public void testInvalidConnections() { public void testInvalidConnections() {
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "name")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "{name")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "{name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "name}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name.values}")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "${name.values}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "$name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "moduleId.outputName.")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "moduleId.outputName."));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "[1].name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "[1].name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "list.[1]name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "list.[1]name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, ".module.array[1].name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, ".module.array[1].name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module1.map\"na[m}.\"e\"]")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module1.map\"na[m}.\"e\"]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.map[\"na[m}.\"e\"")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.map[\"na[m}.\"e\""));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1.name")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1.name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list1].name")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list1].name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1].name.")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.list[1].name."));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module[\"name\"]")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module[\"name\"]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.[name]")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.[name]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module[\"name]")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module[\"name]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.[name\"]")); assertFalse(Pattern.matches(ConnectionValidator.CONNECTION_PATTERN, "module.[name\"]"));
} }
@Test @Test
public void testInvalidConfigReference() { public void testInvalidConfigReference() {
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, ""));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "name")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "{name")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "{name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "name}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name.values}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name.values}"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "[1].name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "[1].name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name.values")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "${name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name.values}")); assertFalse(Pattern.matches(ConnectionValidator.CONFIG_REFERENCE_PATTERN, "$name.values}"));
} }
@Test @Test
public void testValidOutputReference() { public void testValidOutputReference() {
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[1]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[1]"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".phones[1]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".phones[1]"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".phones[1].number")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".phones[1].number"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[\"test\"]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[\"test\"]"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[\"test\"].name")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "[\"test\"].name"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map[\"test\"]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map[\"test\"]"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map[\"test\"].name")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map[\"test\"].name"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.values")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.values"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.array[1]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.array[1]"));
Assert.assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.map[\"na[m}.\"e\"]")); assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.map[\"na[m}.\"e\"]"));
Assert.assertTrue( assertTrue(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.map[\"na[m}.\"e\"].values"));
Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".bean.map[\"na[m}.\"e\"].values"));
} }
@Test @Test
public void testInvalidOutputReference() { public void testInvalidOutputReference() {
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones.")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones."));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones[")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones["));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "]phones")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "]phones"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones[].name")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones[].name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones[\"\"].name")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "phones[\"\"].name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "list.[1]name.values")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "list.[1]name.values"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map\"na[m}.\"e\"]")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, ".map\"na[m}.\"e\"]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.map[\"na[m}.\"e\"")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.map[\"na[m}.\"e\""));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list[1.name")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list[1.name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list1].name")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list1].name"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list[1].name.")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.list[1].name."));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module[\"name\"]")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module[\"name\"]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.[name]")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.[name]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module[\"name]")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module[\"name]"));
Assert.assertTrue(!Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.[name\"]")); assertFalse(Pattern.matches(ConnectionValidator.OUTPUT_REFERENCE_PATTERN, "module.[name\"]"));
} }
} }

View File

@ -12,8 +12,9 @@
*/ */
package org.openhab.core.automation.internal; package org.openhab.core.automation.internal;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.openhab.core.automation.RulePredicates; import org.openhab.core.automation.RulePredicates;
/** /**
@ -34,18 +35,18 @@ public class RulePrefixTest {
@Test @Test
public void testEmptyPrefix() { public void testEmptyPrefix() {
final RuleImpl rule0 = new RuleImpl(null); final RuleImpl rule0 = new RuleImpl(null);
Assert.assertNotNull("Returned UID is null instead of generated one", rule0.getUID()); assertNotNull(rule0.getUID(), "Returned UID is null instead of generated one");
Assert.assertNull("Returned a prefix instead of null", RulePredicates.getPrefix(rule0)); assertNull(RulePredicates.getPrefix(rule0), "Returned a prefix instead of null");
final String somethingWithoutSeparator = "something_without_separator"; final String somethingWithoutSeparator = "something_without_separator";
final RuleImpl rule1 = new RuleImpl(somethingWithoutSeparator); final RuleImpl rule1 = new RuleImpl(somethingWithoutSeparator);
Assert.assertEquals("Returned wrong UID", somethingWithoutSeparator, rule1.getUID()); assertEquals(somethingWithoutSeparator, rule1.getUID(), "Returned wrong UID");
Assert.assertNull("Returned a prefix instead of null", RulePredicates.getPrefix(rule1)); assertNull(RulePredicates.getPrefix(rule1), "Returned a prefix instead of null");
final String withSeparatorButEmpty = RulePredicates.PREFIX_SEPARATOR + "with_separator_but_empty"; final String withSeparatorButEmpty = RulePredicates.PREFIX_SEPARATOR + "with_separator_but_empty";
final RuleImpl rule2 = new RuleImpl(withSeparatorButEmpty); final RuleImpl rule2 = new RuleImpl(withSeparatorButEmpty);
Assert.assertEquals("Returned wrong UID", withSeparatorButEmpty, rule2.getUID()); assertEquals(withSeparatorButEmpty, rule2.getUID(), "Returned wrong UID");
Assert.assertNull("Returned a prefix instead of null", RulePredicates.getPrefix(rule2)); assertNull(RulePredicates.getPrefix(rule2), "Returned a prefix instead of null");
} }
/** /**
@ -60,18 +61,18 @@ public class RulePrefixTest {
final String someName = "someName"; final String someName = "someName";
final RuleImpl rule0 = new RuleImpl(testingPrefixPrefix + someName); final RuleImpl rule0 = new RuleImpl(testingPrefixPrefix + someName);
Assert.assertEquals("Returned wrong prefix", TESTING_PREFIX, RulePredicates.getPrefix(rule0)); assertEquals(TESTING_PREFIX, RulePredicates.getPrefix(rule0), "Returned wrong prefix");
Assert.assertEquals("Returned wrong UID", testingPrefixPrefix + someName, rule0.getUID()); assertEquals(testingPrefixPrefix + someName, rule0.getUID(), "Returned wrong UID");
final String multipleSeparatorName = RulePredicates.PREFIX_SEPARATOR + "nameBetweenSeparator" final String multipleSeparatorName = RulePredicates.PREFIX_SEPARATOR + "nameBetweenSeparator"
+ RulePredicates.PREFIX_SEPARATOR; + RulePredicates.PREFIX_SEPARATOR;
final RuleImpl rule1 = new RuleImpl(testingPrefixPrefix + multipleSeparatorName); final RuleImpl rule1 = new RuleImpl(testingPrefixPrefix + multipleSeparatorName);
Assert.assertEquals("Returned wrong prefix", TESTING_PREFIX, RulePredicates.getPrefix(rule1)); assertEquals(TESTING_PREFIX, RulePredicates.getPrefix(rule1), "Returned wrong prefix");
Assert.assertEquals("Returned wrong UID", testingPrefixPrefix + someName, rule0.getUID()); assertEquals(testingPrefixPrefix + someName, rule0.getUID(), "Returned wrong UID");
final String emptyName = ""; final String emptyName = "";
final RuleImpl rule2 = new RuleImpl(testingPrefixPrefix + emptyName); final RuleImpl rule2 = new RuleImpl(testingPrefixPrefix + emptyName);
Assert.assertEquals("Returned wrong prefix", TESTING_PREFIX, RulePredicates.getPrefix(rule2)); assertEquals(TESTING_PREFIX, RulePredicates.getPrefix(rule2), "Returned wrong prefix");
Assert.assertEquals("Returned wrong UID", testingPrefixPrefix + emptyName, rule2.getUID()); assertEquals(testingPrefixPrefix + emptyName, rule2.getUID(), "Returned wrong UID");
} }
} }

View File

@ -13,14 +13,15 @@
package org.openhab.core.automation.internal.module.factory; package org.openhab.core.automation.internal.module.factory;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.util.Collections; import java.util.Collections;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.automation.Condition; import org.openhab.core.automation.Condition;
import org.openhab.core.automation.Module; import org.openhab.core.automation.Module;
import org.openhab.core.automation.handler.ModuleHandler; import org.openhab.core.automation.handler.ModuleHandler;
@ -39,7 +40,7 @@ public class EphemerisModuleHandlerFactoryTest {
private @NonNullByDefault({}) EphemerisModuleHandlerFactory factory; private @NonNullByDefault({}) EphemerisModuleHandlerFactory factory;
private @NonNullByDefault({}) Module moduleMock; private @NonNullByDefault({}) Module moduleMock;
@Before @BeforeEach
public void setUp() { public void setUp() {
factory = new EphemerisModuleHandlerFactory(mock(EphemerisManager.class)); factory = new EphemerisModuleHandlerFactory(mock(EphemerisManager.class));
@ -47,14 +48,12 @@ public class EphemerisModuleHandlerFactoryTest {
when(moduleMock.getId()).thenReturn("My id"); when(moduleMock.getId()).thenReturn("My id");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testFactoryFailsCreatingModuleHandlerForDaysetCondition() { public void testFactoryFailsCreatingModuleHandlerForDaysetCondition() {
when(moduleMock.getTypeUID()).thenReturn(EphemerisConditionHandler.DAYSET_MODULE_TYPE_ID); when(moduleMock.getTypeUID()).thenReturn(EphemerisConditionHandler.DAYSET_MODULE_TYPE_ID);
when(moduleMock.getConfiguration()).thenReturn(new Configuration()); when(moduleMock.getConfiguration()).thenReturn(new Configuration());
ModuleHandler handler = factory.internalCreate(moduleMock, "My first rule"); assertThrows(IllegalArgumentException.class, () -> factory.internalCreate(moduleMock, "My first rule"));
assertThat(handler, is(notNullValue()));
assertThat(handler, instanceOf(EphemerisConditionHandler.class));
} }
@Test @Test

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.automation.internal.module.provider; package org.openhab.core.automation.internal.module.provider;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -22,8 +22,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.OpenHAB; import org.openhab.core.OpenHAB;
import org.openhab.core.automation.AnnotatedActions; import org.openhab.core.automation.AnnotatedActions;
import org.openhab.core.automation.Visibility; import org.openhab.core.automation.Visibility;
@ -72,7 +72,7 @@ public class AnnotationActionModuleTypeProviderTest extends JavaTest {
private AnnotatedActions actionProviderConf1; private AnnotatedActions actionProviderConf1;
private AnnotatedActions actionProviderConf2; private AnnotatedActions actionProviderConf2;
@Before @BeforeEach
public void setUp() { public void setUp() {
actionProviderConf1 = new TestActionProvider(); actionProviderConf1 = new TestActionProvider();
actionProviderConf2 = new TestActionProvider(); actionProviderConf2 = new TestActionProvider();

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.automation.thingsupport; package org.openhab.core.automation.thingsupport;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -23,8 +23,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.automation.Visibility; import org.openhab.core.automation.Visibility;
import org.openhab.core.automation.annotation.ActionInput; import org.openhab.core.automation.annotation.ActionInput;
import org.openhab.core.automation.annotation.ActionOutput; import org.openhab.core.automation.annotation.ActionOutput;
@ -80,7 +80,7 @@ public class AnnotatedThingActionModuleTypeProviderTest extends JavaTest {
private ThingActions actionProviderConf1; private ThingActions actionProviderConf1;
private ThingActions actionProviderConf2; private ThingActions actionProviderConf2;
@Before @BeforeEach
public void setUp() { public void setUp() {
mockHandler1 = mock(ThingHandler.class); mockHandler1 = mock(ThingHandler.class);
when(mockHandler1.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test1").build()); when(mockHandler1.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test1").build());

View File

@ -12,14 +12,15 @@
*/ */
package org.openhab.core.automation.util; package org.openhab.core.automation.util;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.openhab.core.automation.Module; import org.openhab.core.automation.Module;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -95,17 +96,17 @@ public class ReferenceResolverUtilTest {
Module trigger = ModuleBuilder.createTrigger().withId("id1").withTypeUID("typeUID1") Module trigger = ModuleBuilder.createTrigger().withId("id1").withTypeUID("typeUID1")
.withConfiguration(new Configuration(MODULE_CONFIGURATION)).build(); .withConfiguration(new Configuration(MODULE_CONFIGURATION)).build();
ReferenceResolver.updateConfiguration(trigger.getConfiguration(), CONTEXT, logger); ReferenceResolver.updateConfiguration(trigger.getConfiguration(), CONTEXT, logger);
Assert.assertEquals(trigger.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION)); assertEquals(trigger.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION));
// test condition configuration. // test condition configuration.
Module condition = ModuleBuilder.createCondition().withId("id2").withTypeUID("typeUID2") Module condition = ModuleBuilder.createCondition().withId("id2").withTypeUID("typeUID2")
.withConfiguration(new Configuration(MODULE_CONFIGURATION)).build(); .withConfiguration(new Configuration(MODULE_CONFIGURATION)).build();
ReferenceResolver.updateConfiguration(condition.getConfiguration(), CONTEXT, logger); ReferenceResolver.updateConfiguration(condition.getConfiguration(), CONTEXT, logger);
Assert.assertEquals(condition.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION)); assertEquals(condition.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION));
// test action configuration. // test action configuration.
Module action = ModuleBuilder.createAction().withId("id3").withTypeUID("typeUID3") Module action = ModuleBuilder.createAction().withId("id3").withTypeUID("typeUID3")
.withConfiguration(new Configuration(MODULE_CONFIGURATION)).build(); .withConfiguration(new Configuration(MODULE_CONFIGURATION)).build();
ReferenceResolver.updateConfiguration(action.getConfiguration(), CONTEXT, logger); ReferenceResolver.updateConfiguration(action.getConfiguration(), CONTEXT, logger);
Assert.assertEquals(action.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION)); assertEquals(action.getConfiguration(), new Configuration(EXPECTED_MODULE_CONFIGURATION));
} }
@Test @Test
@ -114,39 +115,39 @@ public class ReferenceResolverUtilTest {
Module condition = ModuleBuilder.createCondition().withId("id1").withTypeUID("typeUID1") Module condition = ModuleBuilder.createCondition().withId("id1").withTypeUID("typeUID1")
.withInputs(COMPOSITE_CHILD_MODULE_INPUTS_REFERENCES).build(); .withInputs(COMPOSITE_CHILD_MODULE_INPUTS_REFERENCES).build();
Map<String, Object> conditionContext = ReferenceResolver.getCompositeChildContext(condition, CONTEXT); Map<String, Object> conditionContext = ReferenceResolver.getCompositeChildContext(condition, CONTEXT);
Assert.assertEquals(conditionContext, EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT); assertEquals(conditionContext, EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT);
// test Composite child ModuleImpl(action) context // test Composite child ModuleImpl(action) context
Module action = ModuleBuilder.createAction().withId("id2").withTypeUID("typeUID2") Module action = ModuleBuilder.createAction().withId("id2").withTypeUID("typeUID2")
.withInputs(COMPOSITE_CHILD_MODULE_INPUTS_REFERENCES).build(); .withInputs(COMPOSITE_CHILD_MODULE_INPUTS_REFERENCES).build();
Assert.assertEquals(EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT, conditionContext); assertEquals(EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT, conditionContext);
Map<String, Object> actionContext = ReferenceResolver.getCompositeChildContext(action, CONTEXT); Map<String, Object> actionContext = ReferenceResolver.getCompositeChildContext(action, CONTEXT);
Assert.assertEquals(actionContext, EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT); assertEquals(actionContext, EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT);
} }
@Test @Test
public void testSplitReferenceToTokens() { public void testSplitReferenceToTokens() {
Assert.assertNull(ReferenceResolver.splitReferenceToTokens(null)); assertNull(ReferenceResolver.splitReferenceToTokens(null));
Assert.assertTrue(ReferenceResolver.splitReferenceToTokens("").length == 0); assertTrue(ReferenceResolver.splitReferenceToTokens("").length == 0);
final String[] referenceTokens = ReferenceResolver final String[] referenceTokens = ReferenceResolver
.splitReferenceToTokens(".module.array[\".na[m}.\"e\"][1].values1"); .splitReferenceToTokens(".module.array[\".na[m}.\"e\"][1].values1");
Assert.assertTrue("module".equals(referenceTokens[0])); assertTrue("module".equals(referenceTokens[0]));
Assert.assertTrue("array".equals(referenceTokens[1])); assertTrue("array".equals(referenceTokens[1]));
Assert.assertTrue(".na[m}.\"e".equals(referenceTokens[2])); assertTrue(".na[m}.\"e".equals(referenceTokens[2]));
Assert.assertTrue("1".equals(referenceTokens[3])); assertTrue("1".equals(referenceTokens[3]));
Assert.assertTrue("values1".equals(referenceTokens[4])); assertTrue("values1".equals(referenceTokens[4]));
} }
@Test @Test
public void testResolvingFromNull() { public void testResolvingFromNull() {
String ken = "Ken"; String ken = "Ken";
Assert.assertEquals(ken, assertEquals(ken,
ReferenceResolver.resolveComplexDataReference(ken, ReferenceResolver.splitReferenceToTokens(null))); ReferenceResolver.resolveComplexDataReference(ken, ReferenceResolver.splitReferenceToTokens(null)));
} }
@Test @Test
public void testResolvingFromEmptyString() { public void testResolvingFromEmptyString() {
String ken = "Ken"; String ken = "Ken";
Assert.assertEquals(ken, assertEquals(ken,
ReferenceResolver.resolveComplexDataReference(ken, ReferenceResolver.splitReferenceToTokens(""))); ReferenceResolver.resolveComplexDataReference(ken, ReferenceResolver.splitReferenceToTokens("")));
} }
@ -154,14 +155,15 @@ public class ReferenceResolverUtilTest {
public void testGetFromList() { public void testGetFromList() {
String ken = "Ken"; String ken = "Ken";
List<String> names = Arrays.asList("John", ken, "Sue"); List<String> names = Arrays.asList("John", ken, "Sue");
Assert.assertEquals(ken, assertEquals(ken,
ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[1]"))); ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[1]")));
} }
@Test(expected = NumberFormatException.class) @Test
public void testGetFromListInvalidIndexFormat() { public void testGetFromListInvalidIndexFormat() {
List<String> names = Arrays.asList("John", "Ken", "Sue"); List<String> names = Arrays.asList("John", "Ken", "Sue");
ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[Ten]")); assertThrows(NumberFormatException.class, () -> ReferenceResolver.resolveComplexDataReference(names,
ReferenceResolver.splitReferenceToTokens("[Ten]")));
} }
@Test @Test
@ -171,7 +173,7 @@ public class ReferenceResolverUtilTest {
phones.put("John", phone); phones.put("John", phone);
phones.put("Sue", "0222 2184 121"); phones.put("Sue", "0222 2184 121");
phones.put("Mark", "0222 5641 121"); phones.put("Mark", "0222 5641 121");
Assert.assertEquals(phone, ReferenceResolver.resolveComplexDataReference(phones, assertEquals(phone, ReferenceResolver.resolveComplexDataReference(phones,
ReferenceResolver.splitReferenceToTokens("[\"John\"]"))); ReferenceResolver.splitReferenceToTokens("[\"John\"]")));
} }
@ -182,7 +184,7 @@ public class ReferenceResolverUtilTest {
phones.put("John[].Smi\"th].", phone); phones.put("John[].Smi\"th].", phone);
phones.put("Sue", "0222 2184 121"); phones.put("Sue", "0222 2184 121");
phones.put("Mark", "0222 5641 121"); phones.put("Mark", "0222 5641 121");
Assert.assertEquals(phone, ReferenceResolver.resolveComplexDataReference(phones, assertEquals(phone, ReferenceResolver.resolveComplexDataReference(phones,
ReferenceResolver.splitReferenceToTokens("[\"John[].Smi\"th].\"]"))); ReferenceResolver.splitReferenceToTokens("[\"John[].Smi\"th].\"]")));
} }
@ -191,7 +193,7 @@ public class ReferenceResolverUtilTest {
Map<String, String> phones = new HashMap<>(); Map<String, String> phones = new HashMap<>();
phones.put("Sue", "0222 2184 121"); phones.put("Sue", "0222 2184 121");
phones.put("Mark", "0222 5641 121"); phones.put("Mark", "0222 5641 121");
Assert.assertNull(ReferenceResolver.resolveComplexDataReference(phones, assertNull(ReferenceResolver.resolveComplexDataReference(phones,
ReferenceResolver.splitReferenceToTokens("[\"John\"]"))); ReferenceResolver.splitReferenceToTokens("[\"John\"]")));
} }
@ -199,27 +201,29 @@ public class ReferenceResolverUtilTest {
public void getFromList() { public void getFromList() {
String ken = "Ken"; String ken = "Ken";
List<String> names = Arrays.asList(new String[] { "John", ken, "Sue" }); List<String> names = Arrays.asList(new String[] { "John", ken, "Sue" });
Assert.assertEquals(ken, assertEquals(ken,
ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[1]"))); ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[1]")));
} }
@Test(expected = ArrayIndexOutOfBoundsException.class) @Test
public void testGetFromListInvalidIndex() { public void testGetFromListInvalidIndex() {
List<String> names = Arrays.asList(new String[] { "John", "Ken", "Sue" }); List<String> names = Arrays.asList(new String[] { "John", "Ken", "Sue" });
ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[10]")); assertThrows(ArrayIndexOutOfBoundsException.class, () -> ReferenceResolver.resolveComplexDataReference(names,
ReferenceResolver.splitReferenceToTokens("[10]")));
} }
@Test(expected = NumberFormatException.class) @Test
public void testGetFromInvalidIndexFormat() { public void testGetFromInvalidIndexFormat() {
List<String> names = Arrays.asList(new String[] { "John", "Ken", "Sue" }); List<String> names = Arrays.asList(new String[] { "John", "Ken", "Sue" });
ReferenceResolver.resolveComplexDataReference(names, ReferenceResolver.splitReferenceToTokens("[Ten]")); assertThrows(NumberFormatException.class, () -> ReferenceResolver.resolveComplexDataReference(names,
ReferenceResolver.splitReferenceToTokens("[Ten]")));
} }
@Test @Test
public void testGetFromBean() { public void testGetFromBean() {
String name = "John"; String name = "John";
B1<String> b3 = new B1<>(name); B1<String> b3 = new B1<>(name);
Assert.assertEquals(name, assertEquals(name,
ReferenceResolver.resolveComplexDataReference(b3, ReferenceResolver.splitReferenceToTokens("value"))); ReferenceResolver.resolveComplexDataReference(b3, ReferenceResolver.splitReferenceToTokens("value")));
} }
@ -227,7 +231,7 @@ public class ReferenceResolverUtilTest {
public void testGetFromBeanWithPrivateField() { public void testGetFromBeanWithPrivateField() {
String name = "John"; String name = "John";
B2<String> b4 = new B2<>(name); B2<String> b4 = new B2<>(name);
Assert.assertEquals(name, assertEquals(name,
ReferenceResolver.resolveComplexDataReference(b4, ReferenceResolver.splitReferenceToTokens("value"))); ReferenceResolver.resolveComplexDataReference(b4, ReferenceResolver.splitReferenceToTokens("value")));
} }
@ -238,7 +242,7 @@ public class ReferenceResolverUtilTest {
phones.put("John", phone); phones.put("John", phone);
B1<Map<String, String>> b3 = new B1<>(phones); B1<Map<String, String>> b3 = new B1<>(phones);
B2<B1<Map<String, String>>> b4 = new B2<>(b3); B2<B1<Map<String, String>>> b4 = new B2<>(b3);
Assert.assertEquals(phone, ReferenceResolver.resolveComplexDataReference(b4, assertEquals(phone, ReferenceResolver.resolveComplexDataReference(b4,
ReferenceResolver.splitReferenceToTokens("value.value[\"John\"]"))); ReferenceResolver.splitReferenceToTokens("value.value[\"John\"]")));
} }
@ -249,7 +253,7 @@ public class ReferenceResolverUtilTest {
B1<String> b32 = new B1<>("Sue"); B1<String> b32 = new B1<>("Sue");
B1<String> b33 = new B1<>(name); B1<String> b33 = new B1<>(name);
List<B1<String>> b = Arrays.asList(b31, b32, b33); List<B1<String>> b = Arrays.asList(b31, b32, b33);
Assert.assertEquals(name, ReferenceResolver.resolveComplexDataReference(b, assertEquals(name, ReferenceResolver.resolveComplexDataReference(b,
ReferenceResolver.splitReferenceToTokens("[2].value"))); ReferenceResolver.splitReferenceToTokens("[2].value")));
} }

View File

@ -13,15 +13,15 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import java.net.URI; import java.net.URI;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type; import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
/** /**
@ -42,7 +42,7 @@ public class ConfigDescriptionBuilderTest {
.create("TEST GROUP 2").withAdvanced(Boolean.TRUE).withLabel("Test Group 2").build(); .create("TEST GROUP 2").withAdvanced(Boolean.TRUE).withLabel("Test Group 2").build();
private ConfigDescriptionBuilder builder; private ConfigDescriptionBuilder builder;
@Before @BeforeEach
public void setup() { public void setup() {
builder = ConfigDescriptionBuilder.create(CONFIG_URI); builder = ConfigDescriptionBuilder.create(CONFIG_URI);
} }

View File

@ -13,12 +13,13 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Arrays; import java.util.Arrays;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type; import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
/** /**
@ -163,43 +164,51 @@ public class ConfigDescriptionParameterBuilderTest {
assertTrue(param2.getOptions().isEmpty()); assertTrue(param2.getOptions().isEmpty());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatNameMustNotBeNull() { public void assertThatNameMustNotBeNull() {
ConfigDescriptionParameterBuilder.create(null, Type.BOOLEAN).build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create(null, Type.BOOLEAN).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatNameMustNotBeEmpty() { public void assertThatNameMustNotBeEmpty() {
ConfigDescriptionParameterBuilder.create("", Type.BOOLEAN).build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("", Type.BOOLEAN).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatTypeMustNotBeNull() { public void assertThatTypeMustNotBeNull() {
ConfigDescriptionParameterBuilder.create("Dummy", null).build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", null).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUnitForTextParameterIsNotAllowed() { public void assertThatUnitForTextParameterIsNotAllowed() {
ConfigDescriptionParameterBuilder.create("Dummy", Type.TEXT).withUnit("m").build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", Type.TEXT).withUnit("m").build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUnitForBooleanParameterIsNotAllowed() { public void assertThatUnitForBooleanParameterIsNotAllowed() {
ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnit("m").build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnit("m").build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUnitLabelForTextParameterIsNotAllowed() { public void assertThatUnitLabelForTextParameterIsNotAllowed() {
ConfigDescriptionParameterBuilder.create("Dummy", Type.TEXT).withUnitLabel("Runs").build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", Type.TEXT).withUnitLabel("Runs").build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUnitLabelForBooleanParameterIsNotAllowed() { public void assertThatUnitLabelForBooleanParameterIsNotAllowed() {
ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnitLabel("Runs").build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnitLabel("Runs").build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatAparameterWithAnInvalidUnitCannotBeCreated() { public void assertThatAparameterWithAnInvalidUnitCannotBeCreated() {
ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnit("invalid").build(); assertThrows(IllegalArgumentException.class,
() -> ConfigDescriptionParameterBuilder.create("Dummy", Type.BOOLEAN).withUnit("invalid").build());
} }
} }

View File

@ -13,11 +13,11 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests for {@link ConfigDescriptionParameterGroupBuilder) class. * Tests for {@link ConfigDescriptionParameterGroupBuilder) class.
@ -29,7 +29,7 @@ public class ConfigDescriptionParameterGroupBuilderTest {
private @NonNullByDefault({}) ConfigDescriptionParameterGroupBuilder builder; private @NonNullByDefault({}) ConfigDescriptionParameterGroupBuilder builder;
@Before @BeforeEach
public void setup() { public void setup() {
builder = ConfigDescriptionParameterGroupBuilder.create("test") // builder = ConfigDescriptionParameterGroupBuilder.create("test") //
.withContext("My Context") // .withContext("My Context") //

View File

@ -13,20 +13,23 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.test.java.JavaTest; import org.openhab.core.test.java.JavaTest;
/** /**
@ -34,6 +37,8 @@ import org.openhab.core.test.java.JavaTest;
* *
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class ConfigDescriptionRegistryTest extends JavaTest { public class ConfigDescriptionRegistryTest extends JavaTest {
private URI uriDummy; private URI uriDummy;
@ -52,10 +57,8 @@ public class ConfigDescriptionRegistryTest extends JavaTest {
private @Mock ConfigOptionProvider configOptionsProviderMockAliased; private @Mock ConfigOptionProvider configOptionsProviderMockAliased;
private @Mock ConfigOptionProvider configOptionsProviderMock; private @Mock ConfigOptionProvider configOptionsProviderMock;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
initMocks(this);
uriDummy = new URI("config:Dummy"); uriDummy = new URI("config:Dummy");
uriDummy1 = new URI("config:Dummy1"); uriDummy1 = new URI("config:Dummy1");
uriAliases = new URI("config:Aliased"); uriAliases = new URI("config:Aliased");

View File

@ -13,7 +13,7 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.openhab.core.config.core.ConfigDescriptionParameter.Type.*; import static org.openhab.core.config.core.ConfigDescriptionParameter.Type.*;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -23,7 +23,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution

View File

@ -13,8 +13,8 @@
package org.openhab.core.config.core; package org.openhab.core.config.core;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThat; import static org.hamcrest.core.IsIterableContaining.hasItems;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,7 +24,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test for Configuration class. * Test for Configuration class.

View File

@ -13,14 +13,14 @@
package org.openhab.core.config.core.internal.i18n; package org.openhab.core.config.core.internal.i18n;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.net.URI; import java.net.URI;
import java.util.Locale; import java.util.Locale;
import org.hamcrest.collection.IsEmptyCollection; import org.hamcrest.collection.IsEmptyCollection;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ParameterOption; import org.openhab.core.config.core.ParameterOption;
/** /**
@ -38,7 +38,7 @@ public class I18nConfigOptionsProviderTest {
private final ParameterOption expectedCntryFRJava9 = new ParameterOption("US", "États-Unis"); private final ParameterOption expectedCntryFRJava9 = new ParameterOption("US", "États-Unis");
private URI uriI18N; private URI uriI18N;
@Before @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
provider = new I18nConfigOptionsProvider(); provider = new I18nConfigOptionsProvider();
uriI18N = new URI("system:i18n"); uriI18N = new URI("system:i18n");

View File

@ -12,10 +12,9 @@
*/ */
package org.openhab.core.config.core.internal.metadata; package org.openhab.core.config.core.internal.metadata;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.openhab.core.config.core.internal.metadata.MetadataConfigDescriptionProviderImpl.*; import static org.openhab.core.config.core.internal.metadata.MetadataConfigDescriptionProviderImpl.*;
import java.net.URI; import java.net.URI;
@ -23,9 +22,13 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Locale; import java.util.Locale;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.config.core.ConfigDescription; import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionParameter; import org.openhab.core.config.core.ConfigDescriptionParameter;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type; import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
@ -38,6 +41,8 @@ import org.openhab.core.test.java.JavaTest;
* *
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class MetadataConfigDescriptionProviderImplTest extends JavaTest { public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
private static final String LIBERAL = "liberal"; private static final String LIBERAL = "liberal";
@ -53,9 +58,8 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
private MetadataConfigDescriptionProviderImpl service; private MetadataConfigDescriptionProviderImpl service;
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
service = new MetadataConfigDescriptionProviderImpl(); service = new MetadataConfigDescriptionProviderImpl();
when(mockProviderRestricted.getNamespace()).thenReturn(RESTRICTED); when(mockProviderRestricted.getNamespace()).thenReturn(RESTRICTED);

View File

@ -14,14 +14,14 @@ package org.openhab.core.config.core.internal.normalization;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter; import org.openhab.core.config.core.ConfigDescriptionParameter;
import org.openhab.core.config.core.ConfigDescriptionParameterBuilder; import org.openhab.core.config.core.ConfigDescriptionParameterBuilder;

View File

@ -14,7 +14,8 @@ package org.openhab.core.config.core.internal.validation;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -28,8 +29,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.openhab.core.config.core.ConfigDescription; import org.openhab.core.config.core.ConfigDescription;
@ -147,7 +148,7 @@ public class ConfigDescriptionValidatorTest {
private Map<String, Object> params; private Map<String, Object> params;
private ConfigDescriptionValidatorImpl configDescriptionValidator; private ConfigDescriptionValidatorImpl configDescriptionValidator;
@Before @BeforeEach
public void setUp() { public void setUp() {
ConfigDescriptionRegistry configDescriptionRegistry = mock(ConfigDescriptionRegistry.class); ConfigDescriptionRegistry configDescriptionRegistry = mock(ConfigDescriptionRegistry.class);
when(configDescriptionRegistry.getConfigDescription(any())).thenAnswer(new Answer<ConfigDescription>() { when(configDescriptionRegistry.getConfigDescription(any())).thenAnswer(new Answer<ConfigDescription>() {
@ -481,14 +482,15 @@ public class ConfigDescriptionValidatorTest {
configDescriptionValidator.validate(params, CONFIG_DESCRIPTION_URI); configDescriptionValidator.validate(params, CONFIG_DESCRIPTION_URI);
} }
@Test(expected = NullPointerException.class) @Test
public void assertValidateThrowsNPEforNullParamerters() { public void assertValidateThrowsNPEforNullParamerters() {
configDescriptionValidator.validate(null, CONFIG_DESCRIPTION_URI); assertThrows(NullPointerException.class,
() -> configDescriptionValidator.validate(null, CONFIG_DESCRIPTION_URI));
} }
@Test(expected = NullPointerException.class) @Test
public void assertValidateThrowsNPEforNullConfigDescriptionUri() { public void assertValidateThrowsNPEforNullConfigDescriptionUri() {
configDescriptionValidator.validate(params, null); assertThrows(NullPointerException.class, () -> configDescriptionValidator.validate(params, null));
} }
@Test @Test

View File

@ -15,7 +15,8 @@ package org.openhab.core.config.core.internal.validation;
import static java.util.Collections.*; import static java.util.Collections.*;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.Collection; import java.util.Collection;
@ -25,7 +26,7 @@ import java.util.Map;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.openhab.core.config.core.validation.ConfigValidationException; import org.openhab.core.config.core.validation.ConfigValidationException;
import org.openhab.core.config.core.validation.ConfigValidationMessage; import org.openhab.core.config.core.validation.ConfigValidationMessage;
@ -140,10 +141,11 @@ public class ConfigValidationExceptionTest {
assertThat(messages.get(PARAM2), is(TXT_DEFAULT2)); assertThat(messages.get(PARAM2), is(TXT_DEFAULT2));
} }
@Test(expected = NullPointerException.class) @Test
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void assertThatNPEisThrownForNullConfigValidationMessages() { public void assertThatNPEisThrownForNullConfigValidationMessages() {
new ConfigValidationException(BUNDLE, TRANSLATION_PROVIDER, null); assertThrows(NullPointerException.class,
() -> new ConfigValidationException(BUNDLE, TRANSLATION_PROVIDER, null));
} }
static ConfigValidationMessage createMessage(String parameterName, String defaultMessage, String messageKey, static ConfigValidationMessage createMessage(String parameterName, String defaultMessage, String messageKey,

View File

@ -15,12 +15,13 @@ package org.openhab.core.config.core.status;
import static java.util.Collections.*; import static java.util.Collections.*;
import static java.util.stream.Collectors.*; import static java.util.stream.Collectors.*;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.status.ConfigStatusMessage.Type; import org.openhab.core.config.core.status.ConfigStatusMessage.Type;
/** /**
@ -88,16 +89,16 @@ public class ConfigStatusInfoTest {
assertConfigStatusInfo(info); assertConfigStatusInfo(info);
} }
@Test(expected = NullPointerException.class) @Test
public void assertNPEisThrownIfTypesAreNull() { public void assertNPEisThrownIfTypesAreNull() {
ConfigStatusInfo info = new ConfigStatusInfo(); ConfigStatusInfo info = new ConfigStatusInfo();
info.getConfigStatusMessages(null, emptySet()); assertThrows(NullPointerException.class, () -> info.getConfigStatusMessages(null, emptySet()));
} }
@Test(expected = NullPointerException.class) @Test
public void assertNPEisThrownIfParameterNamesAreNull() { public void assertNPEisThrownIfParameterNamesAreNull() {
ConfigStatusInfo info = new ConfigStatusInfo(); ConfigStatusInfo info = new ConfigStatusInfo();
info.getConfigStatusMessages(emptySet(), null); assertThrows(NullPointerException.class, () -> info.getConfigStatusMessages(emptySet(), null));
} }
private void assertConfigStatusInfo(ConfigStatusInfo info) { private void assertConfigStatusInfo(ConfigStatusInfo info) {

View File

@ -13,7 +13,7 @@
package org.openhab.core.config.core.status; package org.openhab.core.config.core.status;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -23,8 +23,8 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Locale; import java.util.Locale;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.status.ConfigStatusMessage.Type; import org.openhab.core.config.core.status.ConfigStatusMessage.Type;
import org.openhab.core.events.EventPublisher; import org.openhab.core.events.EventPublisher;
import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.LocaleProvider;
@ -80,7 +80,7 @@ public class ConfigStatusServiceTest extends JavaTest {
private final Collection<ConfigStatusMessage> messagesEntity1En = new ArrayList<>(); private final Collection<ConfigStatusMessage> messagesEntity1En = new ArrayList<>();
private final Collection<ConfigStatusMessage> messagesEntity2En = new ArrayList<>(); private final Collection<ConfigStatusMessage> messagesEntity2En = new ArrayList<>();
@Before @BeforeEach
public void setUp() { public void setUp() {
messagesEntity1.add(PARAM1_MSG1); messagesEntity1.add(PARAM1_MSG1);
messagesEntity1.add(PARAM2_MSG2); messagesEntity1.add(PARAM2_MSG2);

View File

@ -13,7 +13,7 @@
package org.openhab.core.config.discovery.inbox; package org.openhab.core.config.discovery.inbox;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.openhab.core.config.discovery.inbox.InboxPredicates.*; import static org.openhab.core.config.discovery.inbox.InboxPredicates.*;
import java.util.AbstractMap.SimpleEntry; import java.util.AbstractMap.SimpleEntry;
@ -25,8 +25,8 @@ import java.util.Map.Entry;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryResultFlag; import org.openhab.core.config.discovery.DiscoveryResultFlag;
@ -76,7 +76,7 @@ public class InboxPredicatesTest {
DiscoveryResultBuilder.create(THING_UID22).withThingType(THING_TYPE_UID21).withProperties(PROPS2) DiscoveryResultBuilder.create(THING_UID22).withThingType(THING_TYPE_UID21).withProperties(PROPS2)
.withLabel("label").build()); .withLabel("label").build());
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
((DiscoveryResultImpl) RESULTS.get(3)).setFlag(DiscoveryResultFlag.IGNORED); ((DiscoveryResultImpl) RESULTS.get(3)).setFlag(DiscoveryResultFlag.IGNORED);
} }

View File

@ -13,9 +13,9 @@
package org.openhab.core.config.discovery.inbox.events; package org.openhab.core.config.discovery.inbox.events;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.dto.DiscoveryResultDTOMapper; import org.openhab.core.config.discovery.dto.DiscoveryResultDTOMapper;

View File

@ -13,11 +13,10 @@
package org.openhab.core.config.discovery.internal; package org.openhab.core.config.discovery.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.openhab.core.config.discovery.inbox.InboxPredicates.withFlag; import static org.openhab.core.config.discovery.inbox.InboxPredicates.withFlag;
import java.util.Collections; import java.util.Collections;
@ -27,11 +26,15 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.config.core.ConfigDescriptionRegistry; import org.openhab.core.config.core.ConfigDescriptionRegistry;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
@ -58,6 +61,8 @@ import org.openhab.core.thing.type.ThingTypeRegistry;
* @author Andre Fuechsel - Initial contribution * @author Andre Fuechsel - Initial contribution
* @author Henning Sudbrock - Added tests for auto-approving inbox entries * @author Henning Sudbrock - Added tests for auto-approving inbox entries
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class AutomaticInboxProcessorTest { public class AutomaticInboxProcessorTest {
private static final String DEVICE_ID = "deviceId"; private static final String DEVICE_ID = "deviceId";
@ -90,37 +95,18 @@ public class AutomaticInboxProcessorTest {
private AutomaticInboxProcessor automaticInboxProcessor; private AutomaticInboxProcessor automaticInboxProcessor;
private PersistentInbox inbox; private PersistentInbox inbox;
@Mock private @Mock ThingRegistry thingRegistry;
private ThingRegistry thingRegistry; private @Mock ThingTypeRegistry thingTypeRegistry;
private @Mock Thing thing;
private @Mock Thing thing2;
private @Mock Thing thing3;
private @Mock ThingStatusInfoChangedEvent thingStatusInfoChangedEvent;
private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private @Mock ThingHandlerFactory thingHandlerFactory;
private @Mock ManagedThingProvider thingProvider;
@Mock @BeforeEach
private ThingTypeRegistry thingTypeRegistry;
@Mock
private Thing thing;
@Mock
private Thing thing2;
@Mock
private Thing thing3;
@Mock
private ThingStatusInfoChangedEvent thingStatusInfoChangedEvent;
@Mock
private ConfigDescriptionRegistry configDescriptionRegistry;
@Mock
private ThingHandlerFactory thingHandlerFactory;
@Mock
private ManagedThingProvider thingProvider;
@Before
public void setUp() { public void setUp() {
initMocks(this);
when(thing.getConfiguration()).thenReturn(CONFIG); when(thing.getConfiguration()).thenReturn(CONFIG);
when(thing.getThingTypeUID()).thenReturn(THING_TYPE_UID); when(thing.getThingTypeUID()).thenReturn(THING_TYPE_UID);
when(thing.getProperties()).thenReturn(THING_PROPERTIES); when(thing.getProperties()).thenReturn(THING_PROPERTIES);
@ -163,7 +149,7 @@ public class AutomaticInboxProcessorTest {
automaticInboxProcessor.activate(null); automaticInboxProcessor.activate(null);
} }
@After @AfterEach
public void tearDown() { public void tearDown() {
automaticInboxProcessor.deactivate(); automaticInboxProcessor.deactivate();
} }
@ -447,7 +433,7 @@ public class AutomaticInboxProcessorTest {
} }
@Test @Test
@Ignore("Should this test pass? It will fail currently, as RuntimeExceptions are not explicitly caught in AutomaticInboxProcessor#isToBeAutoApproved") @Disabled("Should this test pass? It will fail currently, as RuntimeExceptions are not explicitly caught in AutomaticInboxProcessor#isToBeAutoApproved")
public void testRogueInboxAutoApprovePredicatesDoNoHarm() { public void testRogueInboxAutoApprovePredicatesDoNoHarm() {
automaticInboxProcessor.addInboxAutoApprovePredicate(discoveryResult -> { automaticInboxProcessor.addInboxAutoApprovePredicate(discoveryResult -> {
throw new RuntimeException("I am an evil inboxAutoApprovePredicate"); throw new RuntimeException("I am an evil inboxAutoApprovePredicate");

View File

@ -12,12 +12,12 @@
*/ */
package org.openhab.core.config.discovery.internal; package org.openhab.core.config.discovery.internal;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultFlag; import org.openhab.core.config.discovery.DiscoveryResultFlag;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
@ -36,16 +36,18 @@ public class DiscoveryResultImplTest {
private static final int DEFAULT_TTL = 60; private static final int DEFAULT_TTL = 60;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidConstructorForThingType() { public void testInvalidConstructorForThingType() {
new DiscoveryResultImpl(null, new ThingUID("aa"), null, null, null, null, DEFAULT_TTL); assertThrows(IllegalArgumentException.class,
() -> new DiscoveryResultImpl(null, new ThingUID("aa"), null, null, null, null, DEFAULT_TTL));
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidConstructorForTTL() { public void testInvalidConstructorForTTL() {
ThingTypeUID thingTypeUID = new ThingTypeUID("bindingId", "thingType"); ThingTypeUID thingTypeUID = new ThingTypeUID("bindingId", "thingType");
new DiscoveryResultImpl(thingTypeUID, new ThingUID(thingTypeUID, "thingId"), null, null, null, null, -2); assertThrows(IllegalArgumentException.class, () -> new DiscoveryResultImpl(thingTypeUID,
new ThingUID(thingTypeUID, "thingId"), null, null, null, null, -2));
} }
@Test @Test
@ -61,7 +63,7 @@ public class DiscoveryResultImplTest {
assertEquals("", discoveryResult.getLabel()); assertEquals("", discoveryResult.getLabel());
assertEquals(DiscoveryResultFlag.NEW, discoveryResult.getFlag()); assertEquals(DiscoveryResultFlag.NEW, discoveryResult.getFlag());
assertNotNull("The properties must never be null!", discoveryResult.getProperties()); assertNotNull(discoveryResult.getProperties(), "The properties must never be null!");
assertNull(discoveryResult.getRepresentationProperty()); assertNull(discoveryResult.getRepresentationProperty());
} }

View File

@ -12,11 +12,11 @@
*/ */
package org.openhab.core.config.discovery.internal; package org.openhab.core.config.discovery.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.net.URI; import java.net.URI;
@ -25,10 +25,14 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.config.core.ConfigDescription; import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionBuilder; import org.openhab.core.config.core.ConfigDescriptionBuilder;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type; import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
@ -57,38 +61,26 @@ import org.openhab.core.thing.type.ThingTypeRegistry;
/** /**
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class PersistentInboxTest { public class PersistentInboxTest {
private static final ThingTypeUID THING_TYPE_UID = new ThingTypeUID("test", "test"); private static final ThingTypeUID THING_TYPE_UID = new ThingTypeUID("test", "test");
private static final ThingUID THING_UID = new ThingUID(THING_TYPE_UID, "test"); private static final ThingUID THING_UID = new ThingUID(THING_TYPE_UID, "test");
private PersistentInbox inbox; private PersistentInbox inbox;
@Mock
private ThingRegistry thingRegistry;
private Thing lastAddedThing = null; private Thing lastAddedThing = null;
@Mock private @Mock ThingRegistry thingRegistry;
private StorageService storageService; private @Mock StorageService storageService;
private @Mock Storage<Object> storage;
private @Mock ManagedThingProvider thingProvider;
private @Mock ThingTypeRegistry thingTypeRegistry;
private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private @Mock ThingHandlerFactory thingHandlerFactory;
@Mock @BeforeEach
private Storage<Object> storage;
@Mock
private ManagedThingProvider thingProvider;
@Mock
private ThingTypeRegistry thingTypeRegistry;
@Mock
private ConfigDescriptionRegistry configDescriptionRegistry;
@Mock
private ThingHandlerFactory thingHandlerFactory;
@Before
public void setup() { public void setup() {
initMocks(this);
when(storageService.getStorage(any(String.class), any(ClassLoader.class))).thenReturn(storage); when(storageService.getStorage(any(String.class), any(ClassLoader.class))).thenReturn(storage);
doAnswer(invocation -> lastAddedThing = (Thing) invocation.getArguments()[0]).when(thingRegistry) doAnswer(invocation -> lastAddedThing = (Thing) invocation.getArguments()[0]).when(thingRegistry)
.add(any(Thing.class)); .add(any(Thing.class));

View File

@ -13,7 +13,6 @@
package org.openhab.core.config.dispatch.internal; package org.openhab.core.config.dispatch.internal;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.File; import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;
@ -21,24 +20,24 @@ import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent; import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchEvent.Kind;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/** /**
* @author Stefan Triller - Initial contribution * @author Stefan Triller - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class ConfigDispatcherFileWatcherTest { public class ConfigDispatcherFileWatcherTest {
private TestConfigDispatcherFileWatcher configDispatcherFileWatcher; private TestConfigDispatcherFileWatcher configDispatcherFileWatcher;
@Mock private @Mock ConfigDispatcher configDispatcher;
ConfigDispatcher configDispatcher;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
initMocks(this);
configDispatcherFileWatcher = new TestConfigDispatcherFileWatcher(configDispatcher); configDispatcherFileWatcher = new TestConfigDispatcherFileWatcher(configDispatcher);
} }

View File

@ -12,14 +12,14 @@
*/ */
package org.openhab.core.id; package org.openhab.core.id;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.OpenHAB; import org.openhab.core.OpenHAB;
/** /**

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.core.io.bin2json; package org.openhab.core.io.bin2json;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -29,9 +29,10 @@ import com.google.gson.JsonObject;
*/ */
public class Bin2JsonTest { public class Bin2JsonTest {
@Test(expected = ConversionException.class) @Test
public void testParserRuleError() throws ConversionException { public void testParserRuleError() throws ConversionException {
new Bin2Json("byte a byte b ubyte c;").convert(new byte[] { 3, 34, (byte) 255 }); assertThrows(ConversionException.class,
() -> new Bin2Json("byte a byte b ubyte c;").convert(new byte[] { 3, 34, (byte) 255 }));
} }
@Test @Test
@ -40,9 +41,9 @@ public class Bin2JsonTest {
assertEquals("{\"a\":3,\"b\":-6,\"c\":255}", json.toString()); assertEquals("{\"a\":3,\"b\":-6,\"c\":255}", json.toString());
} }
@Test(expected = ConversionException.class) @Test
public void testHexStringDataError() throws ConversionException { public void testHexStringDataError() throws ConversionException {
new Bin2Json("byte a; byte b; ubyte c;").convert("0322F"); assertThrows(ConversionException.class, () -> new Bin2Json("byte a; byte b; ubyte c;").convert("0322F"));
} }
@Test @Test
@ -52,9 +53,10 @@ public class Bin2JsonTest {
assertEquals("{\"length\":4,\"data\":[8,33,1,2]}", json.toString()); assertEquals("{\"length\":4,\"data\":[8,33,1,2]}", json.toString());
} }
@Test(expected = ConversionException.class) @Test
public void testByteArrayDataError() throws ConversionException { public void testByteArrayDataError() throws ConversionException {
new Bin2Json("byte a; byte b; ubyte c;").convert(new byte[] { 3, 34 }); assertThrows(ConversionException.class,
() -> new Bin2Json("byte a; byte b; ubyte c;").convert(new byte[] { 3, 34 }));
} }
@Test @Test
@ -64,9 +66,10 @@ public class Bin2JsonTest {
assertEquals("{\"length\":4,\"data\":[8,33,1,2]}", json.toString()); assertEquals("{\"length\":4,\"data\":[8,33,1,2]}", json.toString());
} }
@Test(expected = ConversionException.class) @Test
public void testInputStreamDataError() throws ConversionException { public void testInputStreamDataError() throws ConversionException {
InputStream inputStream = new ByteArrayInputStream(new byte[] { 4, 8, 33 }); InputStream inputStream = new ByteArrayInputStream(new byte[] { 4, 8, 33 });
new Bin2Json("ubyte length; ubyte[length] data;").convert(inputStream); assertThrows(ConversionException.class,
() -> new Bin2Json("ubyte length; ubyte[length] data;").convert(inputStream));
} }
} }

View File

@ -13,13 +13,14 @@
package org.openhab.core.io.http.internal; package org.openhab.core.io.http.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.io.http.WrappingHttpContext; import org.openhab.core.io.http.WrappingHttpContext;
import org.osgi.framework.Bundle; import org.osgi.framework.Bundle;
import org.osgi.service.http.HttpContext; import org.osgi.service.http.HttpContext;
@ -28,21 +29,18 @@ import org.osgi.service.http.HttpContext;
* *
* @author Łukasz Dywicki - Initial contribution * @author Łukasz Dywicki - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class HttpContextFactoryServiceImplTest { public class HttpContextFactoryServiceImplTest {
private static final String RESOURCE = "resource"; private static final String RESOURCE = "resource";
private HttpContextFactoryServiceImpl httpContextFactoryService; private HttpContextFactoryServiceImpl httpContextFactoryService;
@Mock private @Mock Bundle bundle;
private Bundle bundle; private @Mock WrappingHttpContext httpContext;
@Mock @BeforeEach
private WrappingHttpContext httpContext;
@Before
public void setup() { public void setup() {
initMocks(this);
httpContextFactoryService = new HttpContextFactoryServiceImpl(); httpContextFactoryService = new HttpContextFactoryServiceImpl();
httpContextFactoryService.setHttpContext(httpContext); httpContextFactoryService.setHttpContext(httpContext);

View File

@ -12,9 +12,9 @@
*/ */
package org.openhab.core.io.net.exec; package org.openhab.core.io.net.exec;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests for the ExecUtil * Tests for the ExecUtil

View File

@ -14,7 +14,6 @@ package org.openhab.core.io.net.http;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -23,8 +22,12 @@ import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpMethod;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** /**
* Base class for tests for the <code>HttpRequestBuilder</code> and <code>HttpUtil</code> to validate their behavior * Base class for tests for the <code>HttpRequestBuilder</code> and <code>HttpUtil</code> to validate their behavior
@ -32,25 +35,18 @@ import org.mockito.Mock;
* @author Martin van Wingerden & Wouter Born - Initial contribution * @author Martin van Wingerden & Wouter Born - Initial contribution
* @author Markus Rathgeb - Base test classes without tests needs to be abstract * @author Markus Rathgeb - Base test classes without tests needs to be abstract
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public abstract class BaseHttpUtilTest { public abstract class BaseHttpUtilTest {
static final String URL = "http://example.org/test"; static final String URL = "http://example.org/test";
@Mock protected @Mock HttpClientFactory clientFactoryMock;
private HttpClientFactory clientFactoryMock; protected @Mock HttpClient httpClientMock;
protected @Mock Request requestMock;
protected @Mock ContentResponse contentResponseMock;
@Mock @BeforeEach
HttpClient httpClientMock;
@Mock
Request requestMock;
@Mock
ContentResponse contentResponseMock;
@Before
public void setUp() throws Exception { public void setUp() throws Exception {
initMocks(this);
Field httpClientFactory = HttpUtil.class.getDeclaredField("httpClientFactory"); Field httpClientFactory = HttpUtil.class.getDeclaredField("httpClientFactory");
httpClientFactory.setAccessible(true); httpClientFactory.setAccessible(true);
httpClientFactory.set(null, clientFactoryMock); httpClientFactory.set(null, clientFactoryMock);

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.io.net.http; package org.openhab.core.io.net.http;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import java.nio.Buffer; import java.nio.Buffer;
@ -24,7 +24,7 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.api.ContentProvider; import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers; import org.mockito.ArgumentMatchers;

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.io.net.http; package org.openhab.core.io.net.http;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -20,9 +20,7 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/** /**
* Tests for the HttpUtil * Tests for the HttpUtil
@ -32,9 +30,6 @@ import org.junit.rules.ExpectedException;
*/ */
public class HttpUtilTest extends BaseHttpUtilTest { public class HttpUtilTest extends BaseHttpUtilTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test @Test
public void baseTest() throws Exception { public void baseTest() throws Exception {
mockResponse(HttpStatus.OK_200); mockResponse(HttpStatus.OK_200);
@ -71,17 +66,15 @@ public class HttpUtilTest extends BaseHttpUtilTest {
@Test @Test
public void testCreateHttpMethodForUnsupportedFake() { public void testCreateHttpMethodForUnsupportedFake() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Given HTTP Method 'FAKE' is unknown"); () -> HttpUtil.createHttpMethod("FAKE"));
assertEquals("Given HTTP Method 'FAKE' is unknown", exception.getMessage());
HttpUtil.createHttpMethod("FAKE");
} }
@Test @Test
public void testCreateHttpMethodForUnsupportedTrace() { public void testCreateHttpMethodForUnsupportedTrace() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Given HTTP Method 'TRACE' is unknown"); () -> HttpUtil.createHttpMethod("TRACE"));
assertEquals("Given HTTP Method 'TRACE' is unknown", exception.getMessage());
HttpUtil.createHttpMethod("TRACE");
} }
} }

View File

@ -13,7 +13,6 @@
package org.openhab.core.io.net.http.internal; package org.openhab.core.io.net.http.internal;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.Socket; import java.net.Socket;
@ -30,9 +29,13 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager; import javax.net.ssl.X509ExtendedTrustManager;
import javax.security.auth.x500.X500Principal; import javax.security.auth.x500.X500Principal;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.io.net.http.TlsTrustManagerProvider; import org.openhab.core.io.net.http.TlsTrustManagerProvider;
/** /**
@ -40,40 +43,24 @@ import org.openhab.core.io.net.http.TlsTrustManagerProvider;
* *
* @author Martin van Wingerden - Initial contribution * @author Martin van Wingerden - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class ExtensibleTrustManagerImplTest { public class ExtensibleTrustManagerImplTest {
private X509Certificate[] chain;
private ExtensibleTrustManagerImpl subject; private ExtensibleTrustManagerImpl subject;
@Mock private @Mock TlsTrustManagerProvider trustmanagerProvider;
private TlsTrustManagerProvider trustmanagerProvider; private @Mock TlsTrustManagerProvider trustmanagerProviderHostPort;
private @Mock X509ExtendedTrustManager trustmanager;
private @Mock X509ExtendedTrustManager trustmanager2;
private @Mock X509ExtendedTrustManager defaultTrustManager;
private @Mock SSLEngine sslEngine;
private @Mock X509Certificate topOfChain;
private @Mock X509Certificate bottomOfChain;
@Mock @BeforeEach
private TlsTrustManagerProvider trustmanagerProviderHostPort;
@Mock
private X509ExtendedTrustManager trustmanager;
@Mock
private X509ExtendedTrustManager trustmanager2;
@Mock
private X509ExtendedTrustManager defaultTrustManager;
@Mock
private SSLEngine sslEngine;
@Mock
private X509Certificate topOfChain;
@Mock
private X509Certificate bottomOfChain;
private X509Certificate[] chain;
@Before
public void setup() { public void setup() {
initMocks(this);
when(trustmanagerProvider.getHostName()).thenReturn("example.org"); when(trustmanagerProvider.getHostName()).thenReturn("example.org");
when(trustmanagerProvider.getTrustManager()).thenReturn(trustmanager); when(trustmanagerProvider.getTrustManager()).thenReturn(trustmanager);

View File

@ -13,10 +13,10 @@
package org.openhab.core.io.net.http.internal; package org.openhab.core.io.net.http.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
@ -36,17 +36,20 @@ import javax.net.ssl.SSLHandshakeException;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers; import org.mockito.ArgumentMatchers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
/** /**
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class WebClientFactoryImplTest { public class WebClientFactoryImplTest {
private WebClientFactoryImpl webClientFactory; private WebClientFactoryImpl webClientFactory;
@ -55,14 +58,13 @@ public class WebClientFactoryImplTest {
private @Mock ExtensibleTrustManagerImpl extensibleTrustManager; private @Mock ExtensibleTrustManagerImpl extensibleTrustManager;
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
webClientFactory = new WebClientFactoryImpl(extensibleTrustManager); webClientFactory = new WebClientFactoryImpl(extensibleTrustManager);
webClientFactory.activate(createConfigMap(4, 200, 60, 2, 10, 60)); webClientFactory.activate(createConfigMap(4, 200, 60, 2, 10, 60));
} }
@After @AfterEach
public void tearDown() { public void tearDown() {
webClientFactory.deactivate(); webClientFactory.deactivate();
} }
@ -76,8 +78,8 @@ public class WebClientFactoryImplTest {
assertThat(webSocketClient, is(notNullValue())); assertThat(webSocketClient, is(notNullValue()));
} }
@Disabled("connecting to the outside world makes this test flaky")
@Test @Test
@Ignore("connecting to the outside world makes this test flaky")
public void testCommonClientUsesExtensibleTrustManager() throws Exception { public void testCommonClientUsesExtensibleTrustManager() throws Exception {
ArgumentCaptor<X509Certificate[]> certificateChainCaptor = ArgumentCaptor.forClass(X509Certificate[].class); ArgumentCaptor<X509Certificate[]> certificateChainCaptor = ArgumentCaptor.forClass(X509Certificate[].class);
ArgumentCaptor<SSLEngine> sslEngineCaptor = ArgumentCaptor.forClass(SSLEngine.class); ArgumentCaptor<SSLEngine> sslEngineCaptor = ArgumentCaptor.forClass(SSLEngine.class);
@ -97,21 +99,23 @@ public class WebClientFactoryImplTest {
containsString("eclipse.org")); containsString("eclipse.org"));
} }
@Ignore("connecting to the outside world makes this test flaky") @Disabled("connecting to the outside world makes this test flaky")
@Test(expected = SSLHandshakeException.class) @Test
public void testCommonClientUsesExtensibleTrustManagerFailure() throws Throwable { public void testCommonClientUsesExtensibleTrustManagerFailure() throws Throwable {
doThrow(new CertificateException()).when(extensibleTrustManager).checkServerTrusted( doThrow(new CertificateException()).when(extensibleTrustManager).checkServerTrusted(
ArgumentMatchers.any(X509Certificate[].class), anyString(), ArgumentMatchers.any(SSLEngine.class)); ArgumentMatchers.any(X509Certificate[].class), anyString(), ArgumentMatchers.any(SSLEngine.class));
HttpClient httpClient = webClientFactory.getCommonHttpClient(); HttpClient httpClient = webClientFactory.getCommonHttpClient();
assertThrows(SSLHandshakeException.class, () -> {
try { try {
httpClient.GET(TEST_URL); httpClient.GET(TEST_URL);
} catch (ExecutionException e) { } catch (ExecutionException e) {
throw e.getCause(); throw e.getCause();
} }
});
} }
@Ignore("only for manual test") @Disabled("only for manual test")
@Test @Test
public void testMultiThreadedShared() throws Exception { public void testMultiThreadedShared() throws Exception {
ThreadPoolExecutor workers = new ThreadPoolExecutor(20, 80, 60, TimeUnit.SECONDS, ThreadPoolExecutor workers = new ThreadPoolExecutor(20, 80, 60, TimeUnit.SECONDS,
@ -154,7 +158,7 @@ public class WebClientFactoryImplTest {
} }
} }
@Ignore("only for manual test") @Disabled("only for manual test")
@Test @Test
public void testMultiThreadedCustom() throws Exception { public void testMultiThreadedCustom() throws Exception {
ThreadPoolExecutor workers = new ThreadPoolExecutor(20, 80, 60, TimeUnit.SECONDS, ThreadPoolExecutor workers = new ThreadPoolExecutor(20, 80, 60, TimeUnit.SECONDS,

View File

@ -13,13 +13,13 @@
package org.openhab.core.io.rest.core.config; package org.openhab.core.io.rest.core.config;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import java.net.URI; import java.net.URI;
import java.util.Arrays; import java.util.Arrays;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescription; import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionBuilder; import org.openhab.core.config.core.ConfigDescriptionBuilder;
import org.openhab.core.config.core.ConfigDescriptionParameter; import org.openhab.core.config.core.ConfigDescriptionParameter;

View File

@ -13,9 +13,8 @@
package org.openhab.core.io.rest.core.internal.channel; package org.openhab.core.io.rest.core.internal.channel;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
@ -25,14 +24,15 @@ import java.util.Set;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import org.hamcrest.core.IsCollectionContaining; import org.hamcrest.core.IsIterableContaining;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.config.core.ConfigDescriptionRegistry; import org.openhab.core.config.core.ConfigDescriptionRegistry;
import org.openhab.core.io.rest.LocaleServiceImpl; import org.openhab.core.io.rest.LocaleServiceImpl;
import org.openhab.core.thing.profiles.ProfileTypeRegistry; import org.openhab.core.thing.profiles.ProfileTypeRegistry;
import org.openhab.core.thing.profiles.ProfileTypeUID;
import org.openhab.core.thing.profiles.TriggerProfileType; import org.openhab.core.thing.profiles.TriggerProfileType;
import org.openhab.core.thing.type.ChannelKind; import org.openhab.core.thing.type.ChannelKind;
import org.openhab.core.thing.type.ChannelType; import org.openhab.core.thing.type.ChannelType;
@ -42,6 +42,7 @@ import org.openhab.core.thing.type.ChannelTypeUID;
/** /**
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class ChannelTypeResourceTest { public class ChannelTypeResourceTest {
private ChannelTypeResource channelTypeResource; private ChannelTypeResource channelTypeResource;
@ -51,9 +52,8 @@ public class ChannelTypeResourceTest {
private @Mock LocaleServiceImpl localeService; private @Mock LocaleServiceImpl localeService;
private @Mock ProfileTypeRegistry profileTypeRegistry; private @Mock ProfileTypeRegistry profileTypeRegistry;
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
channelTypeResource = new ChannelTypeResource(channelTypeRegistry, configDescriptionRegistry, localeService, channelTypeResource = new ChannelTypeResource(channelTypeRegistry, configDescriptionRegistry, localeService,
profileTypeRegistry); profileTypeRegistry);
} }
@ -70,12 +70,10 @@ public class ChannelTypeResourceTest {
public void returnLinkableItemTypesForTriggerChannelType() throws IOException { public void returnLinkableItemTypesForTriggerChannelType() throws IOException {
ChannelType channelType = mockChannelType("ct"); ChannelType channelType = mockChannelType("ct");
ChannelTypeUID uid = channelType.getUID(); ChannelTypeUID uid = channelType.getUID();
ProfileTypeUID profileTypeUID = new ProfileTypeUID("system:profileType");
when(channelTypeRegistry.getChannelType(uid)).thenReturn(channelType); when(channelTypeRegistry.getChannelType(uid)).thenReturn(channelType);
TriggerProfileType profileType = mock(TriggerProfileType.class); TriggerProfileType profileType = mock(TriggerProfileType.class);
when(profileType.getUID()).thenReturn(profileTypeUID);
when(profileType.getSupportedChannelTypeUIDs()).thenReturn(Collections.singletonList(uid)); when(profileType.getSupportedChannelTypeUIDs()).thenReturn(Collections.singletonList(uid));
when(profileType.getSupportedItemTypes()).thenReturn(Arrays.asList("Switch", "Dimmer")); when(profileType.getSupportedItemTypes()).thenReturn(Arrays.asList("Switch", "Dimmer"));
@ -86,7 +84,7 @@ public class ChannelTypeResourceTest {
verify(channelTypeRegistry).getChannelType(uid); verify(channelTypeRegistry).getChannelType(uid);
verify(profileTypeRegistry).getProfileTypes(); verify(profileTypeRegistry).getProfileTypes();
assertThat(response.getStatus(), is(200)); assertThat(response.getStatus(), is(200));
assertThat((Set<String>) response.getEntity(), IsCollectionContaining.hasItems("Switch", "Dimmer")); assertThat((Set<String>) response.getEntity(), IsIterableContaining.hasItems("Switch", "Dimmer"));
} }
private ChannelType mockChannelType(String channelId) { private ChannelType mockChannelType(String channelId) {

View File

@ -13,12 +13,11 @@
package org.openhab.core.io.rest.core.internal.item; package org.openhab.core.io.rest.core.internal.item;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.IsCollectionContaining.hasItem; import static org.hamcrest.core.IsIterableContaining.hasItem;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
@ -26,9 +25,13 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.config.core.ConfigDescription; import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionBuilder; import org.openhab.core.config.core.ConfigDescriptionBuilder;
import org.openhab.core.config.core.ConfigDescriptionRegistry; import org.openhab.core.config.core.ConfigDescriptionRegistry;
@ -39,20 +42,17 @@ import org.openhab.core.items.MetadataRegistry;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class MetadataSelectorMatcherTest { public class MetadataSelectorMatcherTest {
private MetadataSelectorMatcher matcher; private MetadataSelectorMatcher matcher;
@Mock private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private ConfigDescriptionRegistry configDescriptionRegistry; private @Mock MetadataRegistry metadataRegistry;
@Mock @BeforeEach
private MetadataRegistry metadataRegistry;
@Before
public void setup() throws Exception { public void setup() throws Exception {
initMocks(this);
when(configDescriptionRegistry.getConfigDescriptions(null)).thenReturn(mockConfigDescriptions()); when(configDescriptionRegistry.getConfigDescriptions(null)).thenReturn(mockConfigDescriptions());
when(metadataRegistry.isInternalNamespace(anyString())).thenReturn(false); when(metadataRegistry.isInternalNamespace(anyString())).thenReturn(false);

View File

@ -13,10 +13,10 @@
package org.openhab.core.io.rest.core.item; package org.openhab.core.io.rest.core.item;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.items.GenericItem; import org.openhab.core.items.GenericItem;
import org.openhab.core.items.GroupItem; import org.openhab.core.items.GroupItem;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
@ -29,7 +29,7 @@ public class EnrichedItemDTOMapperTest extends JavaTest {
private CoreItemFactory itemFactory; private CoreItemFactory itemFactory;
@Before @BeforeEach
public void setup() { public void setup() {
itemFactory = new CoreItemFactory(); itemFactory = new CoreItemFactory();
} }

View File

@ -13,11 +13,10 @@
package org.openhab.core.io.rest.core.thing; package org.openhab.core.io.rest.core.thing;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -27,9 +26,11 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.thing.Channel; import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
@ -43,6 +44,7 @@ import org.openhab.core.thing.firmware.dto.FirmwareStatusDTO;
/** /**
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class EnrichedThingDTOMapperTest { public class EnrichedThingDTOMapperTest {
private static final String ITEM_TYPE = "itemType"; private static final String ITEM_TYPE = "itemType";
@ -51,27 +53,15 @@ public class EnrichedThingDTOMapperTest {
private static final String THING_LABEL = "label"; private static final String THING_LABEL = "label";
private static final String LOCATION = "location"; private static final String LOCATION = "location";
@Mock private @Mock Thing thing;
private Thing thing; private @Mock ThingStatusInfo thingStatusInfo;
private @Mock FirmwareStatusDTO firmwareStatus;
private @Mock Map<String, Set<String>> linkedItemsMap;
private @Mock Configuration configuration;
private @Mock Map<String, String> properties;
@Mock @BeforeEach
private ThingStatusInfo thingStatusInfo;
@Mock
private FirmwareStatusDTO firmwareStatus;
@Mock
private Map<String, Set<String>> linkedItemsMap;
@Mock
private Configuration configuration;
@Mock
private Map<String, String> properties;
@Before
public void setup() { public void setup() {
initMocks(this);
when(thing.getThingTypeUID()).thenReturn(new ThingTypeUID(THING_TYPE_UID)); when(thing.getThingTypeUID()).thenReturn(new ThingTypeUID(THING_TYPE_UID));
when(thing.getUID()).thenReturn(new ThingUID(UID)); when(thing.getUID()).thenReturn(new ThingUID(UID));
when(thing.getLabel()).thenReturn(THING_LABEL); when(thing.getLabel()).thenReturn(THING_LABEL);

View File

@ -13,11 +13,10 @@
package org.openhab.core.io.rest.sitemap.internal; package org.openhab.core.io.rest.sitemap.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Collection; import java.util.Collection;
@ -34,9 +33,13 @@ import javax.ws.rs.core.UriInfo;
import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClass;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.io.rest.LocaleService; import org.openhab.core.io.rest.LocaleService;
import org.openhab.core.io.rest.sitemap.SitemapSubscriptionService; import org.openhab.core.io.rest.sitemap.SitemapSubscriptionService;
import org.openhab.core.items.GenericItem; import org.openhab.core.items.GenericItem;
@ -59,6 +62,8 @@ import org.openhab.core.ui.items.ItemUIRegistry;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class SitemapResourceTest extends JavaTest { public class SitemapResourceTest extends JavaTest {
private static final int STATE_UPDATE_WAIT_TIME = 100; private static final int STATE_UPDATE_WAIT_TIME = 100;
@ -96,10 +101,8 @@ public class SitemapResourceTest extends JavaTest {
private EList<Widget> widgets; private EList<Widget> widgets;
@Before @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
initMocks(this);
sitemapResource = new SitemapResource(itemUIRegistry, localeService, subscriptions); sitemapResource = new SitemapResource(itemUIRegistry, localeService, subscriptions);
when(uriInfo.getAbsolutePathBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH)); when(uriInfo.getAbsolutePathBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH));

View File

@ -13,11 +13,11 @@
package org.openhab.core.io.rest.sse.internal.util; package org.openhab.core.io.rest.sse.internal.util;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Dennis Nobel - Initial contribution * @author Dennis Nobel - Initial contribution

View File

@ -13,8 +13,9 @@
package org.openhab.core.io.rest; package org.openhab.core.io.rest;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -27,7 +28,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;

View File

@ -13,7 +13,8 @@
package org.openhab.core.io.rest; package org.openhab.core.io.rest;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -23,7 +24,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Test; import org.junit.jupiter.api.Test;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -39,9 +40,9 @@ public class Stream2JSONInputStreamTest {
private static final Gson GSON = new GsonBuilder().create(); private static final Gson GSON = new GsonBuilder().create();
@Test(expected = IllegalArgumentException.class) @Test
public void shouldFailForNullSource() throws IOException { public void shouldFailForNullSource() throws IOException {
new Stream2JSONInputStream(null).close(); assertThrows(IllegalArgumentException.class, () -> new Stream2JSONInputStream(null).close());
} }
@Test @Test

View File

@ -14,7 +14,7 @@ package org.openhab.core.io.rest.internal.filter;
import static java.util.Collections.*; import static java.util.Collections.*;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.openhab.core.io.rest.internal.filter.CorsFilter.*; import static org.openhab.core.io.rest.internal.filter.CorsFilter.*;
@ -27,12 +27,13 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.MultivaluedMap;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** /**
* Test for the {@link CorsFilter} filter * Test for the {@link CorsFilter} filter
@ -40,6 +41,8 @@ import org.mockito.junit.MockitoRule;
* @author Antoine Besnard - Initial contribution * @author Antoine Besnard - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java and use Mockito * @author Wouter Born - Migrate tests from Groovy to Java and use Mockito
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class CorsFilterTest { public class CorsFilterTest {
private static final String CONTENT_TYPE_HEADER = HttpHeaders.CONTENT_TYPE; private static final String CONTENT_TYPE_HEADER = HttpHeaders.CONTENT_TYPE;
@ -56,9 +59,7 @@ public class CorsFilterTest {
private @Mock ContainerRequestContext requestContext; private @Mock ContainerRequestContext requestContext;
private @Mock ContainerResponseContext responseContext; private @Mock ContainerResponseContext responseContext;
public @Rule MockitoRule mockitoRule = MockitoJUnit.rule(); @BeforeEach
@Before
public void setUp() { public void setUp() {
filter = new CorsFilter(); filter = new CorsFilter();
filter.activate(singletonMap("enable", "true")); filter.activate(singletonMap("enable", "true"));

View File

@ -26,12 +26,13 @@ import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule; import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
/** /**
* Test for {@link ProxyFilter} * Test for {@link ProxyFilter}
@ -39,15 +40,16 @@ import org.mockito.junit.MockitoRule;
* @author Ivan Iliev - Initial contribution * @author Ivan Iliev - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java and use Mockito * @author Wouter Born - Migrate tests from Groovy to Java and use Mockito
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class ProxyFilterTest { public class ProxyFilterTest {
private final ProxyFilter filter = new ProxyFilter(); private final ProxyFilter filter = new ProxyFilter();
private @Mock ContainerRequestContext context; private @Mock ContainerRequestContext context;
private @Mock UriInfo uriInfo; private @Mock UriInfo uriInfo;
public @Rule MockitoRule mockitoRule = MockitoJUnit.rule();
@Before @BeforeEach
public void before() { public void before() {
when(context.getUriInfo()).thenReturn(uriInfo); when(context.getUriInfo()).thenReturn(uriInfo);
} }

View File

@ -13,7 +13,8 @@
package org.openhab.core.io.transport.mqtt; package org.openhab.core.io.transport.mqtt;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -27,7 +28,7 @@ import java.util.concurrent.TimeoutException;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.mqtt.internal.client.MqttAsyncClientWrapper; import org.openhab.core.io.transport.mqtt.internal.client.MqttAsyncClientWrapper;
import org.openhab.core.io.transport.mqtt.reconnect.AbstractReconnectStrategy; import org.openhab.core.io.transport.mqtt.reconnect.AbstractReconnectStrategy;
import org.openhab.core.io.transport.mqtt.reconnect.PeriodicReconnectStrategy; import org.openhab.core.io.transport.mqtt.reconnect.PeriodicReconnectStrategy;
@ -281,29 +282,29 @@ public class MqttBrokerConnectionTests extends JavaTest {
assertArrayEquals(connection.getLastWill().getPayload(), b); assertArrayEquals(connection.getLastWill().getPayload(), b);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void lastWillAndTestamentConstructorTests() { public void lastWillAndTestamentConstructorTests() {
new MqttWillAndTestament("", new byte[0], 0, false); assertThrows(IllegalArgumentException.class, () -> new MqttWillAndTestament("", new byte[0], 0, false));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void qosInvalid() throws ConfigurationException { public void qosInvalid() throws ConfigurationException {
MqttBrokerConnectionEx connection = new MqttBrokerConnectionEx("123.123.123.123", null, false, "qosInvalid"); MqttBrokerConnectionEx connection = new MqttBrokerConnectionEx("123.123.123.123", null, false, "qosInvalid");
connection.setQos(10); assertThrows(IllegalArgumentException.class, () -> connection.setQos(10));
} }
@Test @Test
public void setterGetterTests() { public void setterGetterTests() {
MqttBrokerConnectionEx connection = new MqttBrokerConnectionEx("123.123.123.123", null, false, MqttBrokerConnectionEx connection = new MqttBrokerConnectionEx("123.123.123.123", null, false,
"setterGetterTests"); "setterGetterTests");
assertEquals("URL getter", connection.getHost(), "123.123.123.123"); assertEquals(connection.getHost(), "123.123.123.123", "URL getter");
assertEquals("Name getter", connection.getPort(), 1883); // Check for non-secure port assertEquals(connection.getPort(), 1883, "Name getter"); // Check for non-secure port
assertFalse("Secure getter", connection.isSecure()); assertFalse(connection.isSecure(), "Secure getter");
assertEquals("ClientID getter", "setterGetterTests", connection.getClientId()); assertEquals("setterGetterTests", connection.getClientId(), "ClientID getter");
connection.setCredentials("user@!", "password123@^"); connection.setCredentials("user@!", "password123@^");
assertEquals("User getter/setter", "user@!", connection.getUser()); assertEquals("user@!", connection.getUser(), "User getter/setter");
assertEquals("Password getter/setter", "password123@^", connection.getPassword()); assertEquals("password123@^", connection.getPassword(), "Password getter/setter");
assertEquals(MqttBrokerConnection.DEFAULT_KEEPALIVE_INTERVAL, connection.getKeepAliveInterval()); assertEquals(MqttBrokerConnection.DEFAULT_KEEPALIVE_INTERVAL, connection.getKeepAliveInterval());
connection.setKeepAliveInterval(80); connection.setKeepAliveInterval(80);

View File

@ -13,11 +13,12 @@
package org.openhab.core.io.transport.mqtt.internal; package org.openhab.core.io.transport.mqtt.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.openhab.core.io.transport.mqtt.MqttBrokerConnection; import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
import org.openhab.core.io.transport.mqtt.MqttBrokerConnectionEx; import org.openhab.core.io.transport.mqtt.MqttBrokerConnectionEx;

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.core.io.transport.upnp.internal; package org.openhab.core.io.transport.upnp.internal;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.jupnp.UpnpService; import org.jupnp.UpnpService;
import org.jupnp.controlpoint.ControlPoint; import org.jupnp.controlpoint.ControlPoint;
import org.jupnp.model.meta.DeviceDetails; import org.jupnp.model.meta.DeviceDetails;
@ -32,6 +32,9 @@ import org.jupnp.model.types.UDAServiceId;
import org.jupnp.model.types.UDN; import org.jupnp.model.types.UDN;
import org.jupnp.registry.Registry; import org.jupnp.registry.Registry;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.io.transport.upnp.UpnpIOParticipant; import org.openhab.core.io.transport.upnp.UpnpIOParticipant;
/** /**
@ -39,6 +42,8 @@ import org.openhab.core.io.transport.upnp.UpnpIOParticipant;
* *
* @author Andre Fuechsel - Initial contribution * @author Andre Fuechsel - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class UpnpIOServiceTest { public class UpnpIOServiceTest {
private static final String UDN_1_STRING = "UDN"; private static final String UDN_1_STRING = "UDN";
@ -59,12 +64,9 @@ public class UpnpIOServiceTest {
private UpnpIOServiceImpl upnpIoService; private UpnpIOServiceImpl upnpIoService;
@Before @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
initMocks(this);
when(upnpIoParticipant.getUDN()).thenReturn(UDN_1_STRING); when(upnpIoParticipant.getUDN()).thenReturn(UDN_1_STRING);
when(upnpIoParticipant2.getUDN()).thenReturn(UDN_2_STRING); when(upnpIoParticipant2.getUDN()).thenReturn(UDN_2_STRING);
DeviceIdentity deviceIdentity = new DeviceIdentity(UDN_1); DeviceIdentity deviceIdentity = new DeviceIdentity(UDN_1);

View File

@ -22,10 +22,9 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openhab.core.bundles</groupId> <groupId>org.openhab.core.bundles</groupId>
<artifactId>org.openhab.core.boot</artifactId> <artifactId>org.openhab.core.config.core</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.karaf.features</groupId> <groupId>org.apache.karaf.features</groupId>
<artifactId>org.apache.karaf.features.core</artifactId> <artifactId>org.apache.karaf.features.core</artifactId>

View File

@ -38,7 +38,6 @@ import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService; import org.apache.karaf.features.FeaturesService;
import org.openhab.core.OpenHAB; import org.openhab.core.OpenHAB;
import org.openhab.core.addon.AddonEventFactory; import org.openhab.core.addon.AddonEventFactory;
import org.openhab.core.config.core.ConfigConstants;
import org.openhab.core.config.core.ConfigurableService; import org.openhab.core.config.core.ConfigurableService;
import org.openhab.core.events.Event; import org.openhab.core.events.Event;
import org.openhab.core.events.EventPublisher; import org.openhab.core.events.EventPublisher;
@ -247,7 +246,7 @@ public class FeatureInstaller implements ConfigurationListener {
private void setOnlineRepoUrl() { private void setOnlineRepoUrl() {
Properties prop = new Properties(); Properties prop = new Properties();
Path versionFilePath = Paths.get(ConfigConstants.getUserDataFolder(), "etc", "version.properties"); Path versionFilePath = Paths.get(OpenHAB.getUserDataFolder(), "etc", "version.properties");
try (FileInputStream fis = new FileInputStream(versionFilePath.toFile())) { try (FileInputStream fis = new FileInputStream(versionFilePath.toFile())) {
prop.load(fis); prop.load(fis);
} catch (Exception e) { } catch (Exception e) {

View File

@ -12,40 +12,29 @@
*/ */
package org.openhab.core.model.lsp.internal; package org.openhab.core.model.lsp.internal;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import org.eclipse.emf.common.util.URI; import org.eclipse.emf.common.util.URI;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.io.TempDir;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.rules.TemporaryFolder; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/** /**
* *
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@RunWith(Parameterized.class)
public class MappingUriExtensionsTest { public class MappingUriExtensionsTest {
@Rule public @TempDir File folder;
public final TemporaryFolder folder = new TemporaryFolder();
private File confFolder; private File confFolder;
private File itemsFolder;
private File itemsFile;
private final String conf;
private final String request;
private final String expectedClientPath;
private final String expectedUriPath;
@Parameters private static Collection<Object[]> data() {
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] { // return Arrays.asList(new Object[][] { //
{ "conf", // { "conf", //
"file:///q:/conf", // "file:///q:/conf", //
@ -82,40 +71,38 @@ public class MappingUriExtensionsTest {
}); });
} }
public MappingUriExtensionsTest(String conf, String request, String expectedClientPath, String expectedUriPath) { @BeforeEach
this.conf = conf; public void setup() throws IOException {
this.request = request; confFolder = new File(folder, "conf");
this.expectedClientPath = expectedClientPath;
this.expectedUriPath = expectedUriPath;
}
@Before File itemsFolder = new File(confFolder, "items");
public void setup() throws Exception {
confFolder = folder.newFolder("conf");
itemsFolder = new File(confFolder, "items");
itemsFolder.mkdirs(); itemsFolder.mkdirs();
itemsFile = new File(itemsFolder, "test.items");
File itemsFile = new File(itemsFolder, "test.items");
itemsFile.deleteOnExit(); itemsFile.deleteOnExit();
itemsFile.createNewFile(); itemsFile.createNewFile();
} }
@Test @ParameterizedTest
public void testGuessClientPath() { @MethodSource("data")
MappingUriExtensions mapper = createMapper(); public void testGuessClientPath(String conf, String request, String expectedClientPath, String expectedUriPath) {
MappingUriExtensions mapper = createMapper(conf);
String clientPath = mapper.guessClientPath(request); String clientPath = mapper.guessClientPath(request);
assertEquals(expectedClientPath, clientPath); assertEquals(expectedClientPath, clientPath);
} }
@Test @ParameterizedTest
public void testToUri() { @MethodSource("data")
MappingUriExtensions mapper = createMapper(); public void testToUri(String conf, String request, String expectedClientPath, String expectedUriPath) {
MappingUriExtensions mapper = createMapper(conf);
URI clientPath = mapper.toUri(request); URI clientPath = mapper.toUri(request);
assertEquals(confFolder.toPath().toUri().toString() + expectedUriPath, clientPath.toString()); assertEquals(confFolder.toPath().toUri().toString() + expectedUriPath, clientPath.toString());
} }
@Test @ParameterizedTest
public void testToPathEmfURI() { @MethodSource("data")
MappingUriExtensions mapper = createMapper(); public void testToPathEmfURI(String conf, String request, String expectedClientPath, String expectedUriPath) {
MappingUriExtensions mapper = createMapper(conf);
mapper.toUri(request); mapper.toUri(request);
URI uri = URI.createURI(confFolder.toPath().toUri().toString() + expectedUriPath); URI uri = URI.createURI(confFolder.toPath().toUri().toString() + expectedUriPath);
@ -123,7 +110,7 @@ public class MappingUriExtensionsTest {
assertEquals(request, res); assertEquals(request, res);
} }
private MappingUriExtensions createMapper() { private MappingUriExtensions createMapper(String conf) {
return new MappingUriExtensions(conf) { return new MappingUriExtensions(conf) {
@Override @Override
protected String calcServerLocation(String configFolder) { protected String calcServerLocation(String configFolder) {

View File

@ -13,14 +13,14 @@
package org.openhab.core.model.script.internal.actions; package org.openhab.core.model.script.internal.actions;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.internal.scheduler.SchedulerImpl; import org.openhab.core.internal.scheduler.SchedulerImpl;
import org.openhab.core.model.script.actions.Timer; import org.openhab.core.model.script.actions.Timer;
import org.openhab.core.scheduler.SchedulerRunnable; import org.openhab.core.scheduler.SchedulerRunnable;
@ -41,7 +41,7 @@ public class TimerImplTest {
private final SchedulerImpl scheduler = new SchedulerImpl(); private final SchedulerImpl scheduler = new SchedulerImpl();
private @NonNullByDefault({}) Timer subject; private @NonNullByDefault({}) Timer subject;
@Before @BeforeEach
public void setUp() { public void setUp() {
subject = createTimer(ZonedDateTime.now().plusSeconds(DEFAULT_TIMEOUT_SECONDS), () -> { subject = createTimer(ZonedDateTime.now().plusSeconds(DEFAULT_TIMEOUT_SECONDS), () -> {
Thread.sleep(TimeUnit.SECONDS.toMillis(DEFAULT_RUNTIME_SECONDS)); Thread.sleep(TimeUnit.SECONDS.toMillis(DEFAULT_RUNTIME_SECONDS));

View File

@ -17,7 +17,14 @@ import static org.mockito.Mockito.*;
import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.EList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.model.core.EventType;
import org.openhab.core.model.core.ModelRepository;
import org.openhab.core.model.thing.thing.ModelBridge;
import org.openhab.core.model.thing.thing.ModelThing;
import org.openhab.core.model.thing.thing.ThingModel;
import org.openhab.core.service.ReadyMarker; import org.openhab.core.service.ReadyMarker;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
@ -25,13 +32,6 @@ import org.openhab.core.thing.binding.ThingHandlerFactory;
import org.openhab.core.thing.binding.builder.BridgeBuilder; import org.openhab.core.thing.binding.builder.BridgeBuilder;
import org.openhab.core.thing.binding.builder.ThingBuilder; import org.openhab.core.thing.binding.builder.ThingBuilder;
import org.openhab.core.util.BundleResolver; import org.openhab.core.util.BundleResolver;
import org.openhab.core.model.core.EventType;
import org.openhab.core.model.core.ModelRepository;
import org.openhab.core.model.thing.thing.ModelBridge;
import org.openhab.core.model.thing.thing.ModelThing;
import org.openhab.core.model.thing.thing.ThingModel;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle; import org.osgi.framework.Bundle;
/** /**
@ -55,7 +55,7 @@ public class GenericThingProviderMultipleBundlesTest {
private ThingHandlerFactory bridgeHandlerFactory; private ThingHandlerFactory bridgeHandlerFactory;
private ThingHandlerFactory thingHandlerFactory; private ThingHandlerFactory thingHandlerFactory;
@Before @BeforeEach
public void setup() { public void setup() {
thingProvider = new GenericThingProvider(); thingProvider = new GenericThingProvider();

View File

@ -12,12 +12,12 @@
*/ */
package org.openhab.core.semantics; package org.openhab.core.semantics;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.Locale; import java.util.Locale;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.items.GenericItem; import org.openhab.core.items.GenericItem;
import org.openhab.core.items.GroupItem; import org.openhab.core.items.GroupItem;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
@ -38,7 +38,7 @@ public class SemanticTagsTest {
private GroupItem equipmentItem; private GroupItem equipmentItem;
private GenericItem pointItem; private GenericItem pointItem;
@Before @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
CoreItemFactory itemFactory = new CoreItemFactory(); CoreItemFactory itemFactory = new CoreItemFactory();
locationItem = new GroupItem("TestBathRoom"); locationItem = new GroupItem("TestBathRoom");

View File

@ -12,18 +12,18 @@
*/ */
package org.openhab.core.semantics.internal; package org.openhab.core.semantics.internal;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.items.GenericItem; import org.openhab.core.items.GenericItem;
import org.openhab.core.items.GroupItem; import org.openhab.core.items.GroupItem;
import org.openhab.core.items.Item; import org.openhab.core.items.Item;
@ -36,6 +36,7 @@ import org.openhab.core.semantics.model.location.LivingRoom;
/** /**
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class SemanticsServiceImplTest { public class SemanticsServiceImplTest {
private @Mock ItemRegistry itemRegistry; private @Mock ItemRegistry itemRegistry;
@ -47,10 +48,8 @@ public class SemanticsServiceImplTest {
private SemanticsServiceImpl service; private SemanticsServiceImpl service;
@Before @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
initMocks(this);
CoreItemFactory itemFactory = new CoreItemFactory(); CoreItemFactory itemFactory = new CoreItemFactory();
locationItem = new GroupItem("TestBathRoom"); locationItem = new GroupItem("TestBathRoom");
locationItem.addTag("Bathroom"); locationItem.addTag("Bathroom");
@ -66,7 +65,6 @@ public class SemanticsServiceImplTest {
pointItem.addGroupName(locationItem.getName()); pointItem.addGroupName(locationItem.getName());
locationItem.addMember(pointItem); locationItem.addMember(pointItem);
when(metadataRegistry.get(any())).thenReturn(null);
when(itemRegistry.stream()).thenReturn(Stream.of(locationItem, equipmentItem, pointItem)) when(itemRegistry.stream()).thenReturn(Stream.of(locationItem, equipmentItem, pointItem))
.thenReturn(Stream.of(locationItem, equipmentItem, pointItem)) .thenReturn(Stream.of(locationItem, equipmentItem, pointItem))
.thenReturn(Stream.of(locationItem, equipmentItem, pointItem)); .thenReturn(Stream.of(locationItem, equipmentItem, pointItem));

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.storage.json.internal; package org.openhab.core.storage.json.internal;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -22,8 +22,8 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.test.java.JavaTest; import org.openhab.core.test.java.JavaTest;
@ -37,7 +37,7 @@ public class JsonStorageTest extends JavaTest {
private JsonStorage<DummyObject> objectStorage; private JsonStorage<DummyObject> objectStorage;
private File tmpFile; private File tmpFile;
@Before @BeforeEach
public void setUp() throws IOException { public void setUp() throws IOException {
tmpFile = File.createTempFile("storage-debug", ".json"); tmpFile = File.createTempFile("storage-debug", ".json");
tmpFile.deleteOnExit(); tmpFile.deleteOnExit();

View File

@ -13,15 +13,16 @@
package org.openhab.core.magic.binding.handler; package org.openhab.core.magic.binding.handler;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusInfo; import org.openhab.core.thing.ThingStatusInfo;
@ -33,19 +34,16 @@ import org.openhab.core.thing.binding.ThingHandlerCallback;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class MagicColorLightHandlerTest { public class MagicColorLightHandlerTest {
private ThingHandler handler; private ThingHandler handler;
@Mock private @Mock ThingHandlerCallback callback;
private ThingHandlerCallback callback; private @Mock Thing thing;
@Mock @BeforeEach
private Thing thing;
@Before
public void setUp() { public void setUp() {
initMocks(this);
handler = new MagicColorLightHandler(thing); handler = new MagicColorLightHandler(thing);
handler.setCallback(callback); handler.setCallback(callback);
} }
@ -59,6 +57,6 @@ public class MagicColorLightHandlerTest {
verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture()); verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture());
ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue(); ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue();
Assert.assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE))); assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE)));
} }
} }

View File

@ -13,15 +13,16 @@
package org.openhab.core.magic.binding.handler; package org.openhab.core.magic.binding.handler;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusInfo; import org.openhab.core.thing.ThingStatusInfo;
@ -33,19 +34,16 @@ import org.openhab.core.thing.binding.ThingHandlerCallback;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class MagicDimmableLightHandlerTest { public class MagicDimmableLightHandlerTest {
private ThingHandler handler; private ThingHandler handler;
@Mock private @Mock ThingHandlerCallback callback;
private ThingHandlerCallback callback; private @Mock Thing thing;
@Mock @BeforeEach
private Thing thing;
@Before
public void setUp() { public void setUp() {
initMocks(this);
handler = new MagicDimmableLightHandler(thing); handler = new MagicDimmableLightHandler(thing);
handler.setCallback(callback); handler.setCallback(callback);
} }
@ -59,6 +57,6 @@ public class MagicDimmableLightHandlerTest {
verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture()); verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture());
ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue(); ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue();
Assert.assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE))); assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE)));
} }
} }

View File

@ -13,15 +13,16 @@
package org.openhab.core.magic.binding.handler; package org.openhab.core.magic.binding.handler;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusInfo; import org.openhab.core.thing.ThingStatusInfo;
@ -33,19 +34,16 @@ import org.openhab.core.thing.binding.ThingHandlerCallback;
* *
* @author Henning Treu - Initial contribution * @author Henning Treu - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class MagicOnOffLightHandlerTest { public class MagicOnOffLightHandlerTest {
private ThingHandler handler; private ThingHandler handler;
@Mock private @Mock ThingHandlerCallback callback;
private ThingHandlerCallback callback; private @Mock Thing thing;
@Mock @BeforeEach
private Thing thing;
@Before
public void setUp() { public void setUp() {
initMocks(this);
handler = new MagicOnOffLightHandler(thing); handler = new MagicOnOffLightHandler(thing);
handler.setCallback(callback); handler.setCallback(callback);
} }
@ -59,6 +57,6 @@ public class MagicOnOffLightHandlerTest {
verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture()); verify(callback).statusUpdated(eq(thing), statusInfoCaptor.capture());
ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue(); ThingStatusInfo thingStatusInfo = statusInfoCaptor.getValue();
Assert.assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE))); assertThat(thingStatusInfo.getStatus(), is(equalTo(ThingStatus.ONLINE)));
} }
} }

View File

@ -13,12 +13,12 @@
package org.openhab.core.magic.binding.internal; package org.openhab.core.magic.binding.internal;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.magic.binding.MagicBindingConstants; import org.openhab.core.magic.binding.MagicBindingConstants;
import org.openhab.core.magic.binding.handler.MagicColorLightHandler; import org.openhab.core.magic.binding.handler.MagicColorLightHandler;
import org.openhab.core.magic.binding.handler.MagicDimmableLightHandler; import org.openhab.core.magic.binding.handler.MagicDimmableLightHandler;
@ -36,7 +36,7 @@ public class MagicHandlerFactoryTest {
private @NonNullByDefault({}) MagicHandlerFactory factory; private @NonNullByDefault({}) MagicHandlerFactory factory;
@Before @BeforeEach
public void setup() { public void setup() {
factory = new MagicHandlerFactory(mock(MagicDynamicStateDescriptionProvider.class)); factory = new MagicHandlerFactory(mock(MagicDynamicStateDescriptionProvider.class));
} }

View File

@ -12,14 +12,15 @@
*/ */
package org.openhab.core.magic.binding.internal; package org.openhab.core.magic.binding.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertNull;
import java.net.URI; import java.net.URI;
import java.util.Collection; import java.util.Collection;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ParameterOption; import org.openhab.core.config.core.ParameterOption;
import org.openhab.core.magic.binding.MagicService; import org.openhab.core.magic.binding.MagicService;
@ -34,7 +35,7 @@ public class MagicServiceImplTest {
private MagicService magicService; private MagicService magicService;
@Before @BeforeEach
public void setup() { public void setup() {
magicService = new MagicServiceImpl(); magicService = new MagicServiceImpl();
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.core.test; package org.openhab.core.test;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -33,7 +35,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import org.junit.Assert;
import org.openhab.core.service.ReadyMarker; import org.openhab.core.service.ReadyMarker;
import org.openhab.core.service.ReadyMarkerUtils; import org.openhab.core.service.ReadyMarkerUtils;
import org.openhab.core.service.ReadyService; import org.openhab.core.service.ReadyService;
@ -292,7 +293,7 @@ public class SyntheticBundleInstaller {
ReadyMarker expected = new ReadyMarker(marker, identifier); ReadyMarker expected = new ReadyMarker(marker, identifier);
while (!readyService.isReady(expected)) { while (!readyService.isReady(expected)) {
if (System.nanoTime() - startTime > TimeUnit.SECONDS.toNanos(WAIT_TIMOUT)) { if (System.nanoTime() - startTime > TimeUnit.SECONDS.toNanos(WAIT_TIMOUT)) {
Assert.fail(MessageFormat.format("Timout waiting for marker {0} at bundle {1}", marker, identifier)); fail(MessageFormat.format("Timout waiting for marker {0} at bundle {1}", marker, identifier));
} }
try { try {
Thread.sleep(100); Thread.sleep(100);

View File

@ -13,7 +13,8 @@
package org.openhab.core.test.java; package org.openhab.core.test.java;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -27,9 +28,8 @@ import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before;
import org.openhab.core.test.internal.java.MissingServiceAnalyzer; import org.openhab.core.test.internal.java.MissingServiceAnalyzer;
import org.openhab.core.test.storage.VolatileStorageService; import org.openhab.core.test.storage.VolatileStorageService;
import org.osgi.framework.Bundle; import org.osgi.framework.Bundle;
@ -53,7 +53,7 @@ public class JavaOSGiTest extends JavaTest {
private final Map<String, List<ServiceRegistration<?>>> registeredServices = new HashMap<>(); private final Map<String, List<ServiceRegistration<?>>> registeredServices = new HashMap<>();
protected @NonNullByDefault({}) BundleContext bundleContext; protected @NonNullByDefault({}) BundleContext bundleContext;
@Before @BeforeEach
public void bindBundleContext() { public void bindBundleContext() {
bundleContext = initBundleContext(); bundleContext = initBundleContext();
assertThat(bundleContext, is(notNullValue())); assertThat(bundleContext, is(notNullValue()));
@ -149,7 +149,7 @@ public class JavaOSGiTest extends JavaTest {
*/ */
private <T, I extends T> @Nullable I getSingleServiceInstance(Class<T> clazz, final List<I> filteredServices) { private <T, I extends T> @Nullable I getSingleServiceInstance(Class<T> clazz, final List<I> filteredServices) {
if (filteredServices.size() > 1) { if (filteredServices.size() > 1) {
Assert.fail("More than 1 service matching the filter is registered."); fail("More than 1 service matching the filter is registered.");
} }
if (filteredServices.isEmpty()) { if (filteredServices.isEmpty()) {
new MissingServiceAnalyzer(System.out, bundleContext).printMissingServiceDetails(clazz); new MissingServiceAnalyzer(System.out, bundleContext).printMissingServiceDetails(clazz);
@ -351,7 +351,7 @@ public class JavaOSGiTest extends JavaTest {
registerService(new VolatileStorageService()); registerService(new VolatileStorageService());
} }
@After @AfterEach
public void unregisterMocks() { public void unregisterMocks() {
registeredServices.forEach((interfaceName, services) -> services.forEach(service -> service.unregister())); registeredServices.forEach((interfaceName, services) -> services.forEach(service -> service.unregister()));
registeredServices.clear(); registeredServices.clear();

View File

@ -12,11 +12,11 @@
*/ */
package org.openhab.core.test.java; package org.openhab.core.test.java;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Testing the test. Test suite for the JavaTest base test class. * Testing the test. Test suite for the JavaTest base test class.
@ -27,7 +27,7 @@ public class JavaTestTest {
private JavaTest javaTest; private JavaTest javaTest;
@Before @BeforeEach
public void setup() { public void setup() {
javaTest = new JavaTest(); javaTest = new JavaTest();
} }
@ -49,10 +49,10 @@ public class JavaTestTest {
verify(afterLastCall, times(1)).run(); verify(afterLastCall, times(1)).run();
} }
@Test(expected = NullPointerException.class) @Test
public void waitForAssertShouldNotCatchNPE() { public void waitForAssertShouldNotCatchNPE() {
javaTest.waitForAssert(() -> { assertThrows(NullPointerException.class, () -> {
getObject().getClass(); javaTest.waitForAssert(() -> getObject().getClass());
}); });
} }

View File

@ -14,7 +14,7 @@ package org.openhab.core.thing.xml.internal;
import java.net.URL; import java.net.URL;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* The {@link Example} test case is a usage example how the according {@code ThingType} parser * The {@link Example} test case is a usage example how the according {@code ThingType} parser

View File

@ -13,9 +13,9 @@
package org.openhab.core.thing.xml.internal; package org.openhab.core.thing.xml.internal;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution

View File

@ -12,9 +12,9 @@
*/ */
package org.openhab.core.thing; package org.openhab.core.thing;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests for class {@link ChannelGroupUID}. * Tests for class {@link ChannelGroupUID}.
@ -30,14 +30,14 @@ public class ChannelGroupUIDTest {
private static final ThingUID THING_UID = new ThingUID(BINDING_ID, THING_TYPE_ID, THING_ID); private static final ThingUID THING_UID = new ThingUID(BINDING_ID, THING_TYPE_ID, THING_ID);
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidCharacters() { public void testInvalidCharacters() {
new ChannelGroupUID(THING_UID, "id_with_invalidchar%"); assertThrows(IllegalArgumentException.class, () -> new ChannelGroupUID(THING_UID, "id_with_invalidchar%"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNotEnoughNumberOfSegments() { public void testNotEnoughNumberOfSegments() {
new ChannelUID("binding:thing-type:group"); assertThrows(IllegalArgumentException.class, () -> new ChannelUID("binding:thing-type:group"));
} }
@Test @Test

View File

@ -12,7 +12,7 @@
*/ */
package org.openhab.core.thing; package org.openhab.core.thing;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test cases for the {@link Channel} class. * Test cases for the {@link Channel} class.

View File

@ -12,9 +12,9 @@
*/ */
package org.openhab.core.thing; package org.openhab.core.thing;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests for class {@link ChannelUID}. * Tests for class {@link ChannelUID}.
@ -31,19 +31,20 @@ public class ChannelUIDTest {
private static final String CHANNEL_ID = "id"; private static final String CHANNEL_ID = "id";
private static final ThingUID THING_UID = new ThingUID(BINDING_ID, THING_TYPE_ID, THING_ID); private static final ThingUID THING_UID = new ThingUID(BINDING_ID, THING_TYPE_ID, THING_ID);
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidCharacters() { public void testInvalidCharacters() {
new ChannelUID(THING_UID, "id_with_invalidchar%"); assertThrows(IllegalArgumentException.class, () -> new ChannelUID(THING_UID, "id_with_invalidchar%"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNotEnoughNumberOfSegments() { public void testNotEnoughNumberOfSegments() {
new ChannelUID("binding:thing-type:group#id"); assertThrows(IllegalArgumentException.class, () -> new ChannelUID("binding:thing-type:group#id"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testMultipleChannelGroupSeparators() { public void testMultipleChannelGroupSeparators() {
new ChannelUID("binding:thing-type:thing:group#id#what_ever"); assertThrows(IllegalArgumentException.class,
() -> new ChannelUID("binding:thing-type:thing:group#id#what_ever"));
} }
@Test @Test

View File

@ -12,9 +12,9 @@
*/ */
package org.openhab.core.thing; package org.openhab.core.thing;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* @author Stefan Triller - Initial contribution * @author Stefan Triller - Initial contribution

View File

@ -12,16 +12,18 @@
*/ */
package org.openhab.core.thing; package org.openhab.core.thing;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/** /**
* @author Alex Tugarev - Initial contribution * @author Alex Tugarev - Initial contribution
*/ */
public class UIDTest { public class UIDTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidCharacters() { public void testInvalidCharacters() {
new ThingUID("binding:type:id_with_invalidchar#"); assertThrows(IllegalArgumentException.class, () -> new ThingUID("binding:type:id_with_invalidchar#"));
} }
@Test @Test

View File

@ -13,16 +13,16 @@
package org.openhab.core.thing.binding.builder; package org.openhab.core.thing.binding.builder;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import static org.openhab.core.thing.DefaultSystemChannelTypeProvider.SYSTEM_OUTDOOR_TEMPERATURE; import static org.openhab.core.thing.DefaultSystemChannelTypeProvider.SYSTEM_OUTDOOR_TEMPERATURE;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
import org.openhab.core.thing.Channel; import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
@ -53,7 +53,7 @@ public class ChannelBuilderTest {
private ChannelBuilder builder; private ChannelBuilder builder;
private Channel channel; private Channel channel;
@Before @BeforeEach
public void setup() { public void setup() {
ThingType thingType = ThingTypeBuilder.instance(new ThingTypeUID("bindingId", "thingTypeId"), "thingLabel") ThingType thingType = ThingTypeBuilder.instance(new ThingTypeUID("bindingId", "thingTypeId"), "thingLabel")
.build(); .build();

View File

@ -13,16 +13,17 @@
package org.openhab.core.thing.binding.builder; package org.openhab.core.thing.binding.builder;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
@ -51,7 +52,7 @@ public class ThingBuilderTest {
}; };
private ThingBuilder thingBuilder; private ThingBuilder thingBuilder;
@Before @BeforeEach
public void setup() { public void setup() {
thingBuilder = ThingBuilder.create(THING_TYPE_UID, THING_UID); thingBuilder = ThingBuilder.create(THING_TYPE_UID, THING_UID);
} }
@ -68,26 +69,27 @@ public class ThingBuilderTest {
assertThat(bridgeBuilder.build(), is(instanceOf(BridgeImpl.class))); assertThat(bridgeBuilder.build(), is(instanceOf(BridgeImpl.class)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testWithChannelDuplicates() { public void testWithChannelDuplicates() {
thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build()); thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build());
thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build()); assertThrows(IllegalArgumentException.class,
() -> thingBuilder.withChannel(ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testWithChannelsDuplicatesCollections() { public void testWithChannelsDuplicatesCollections() {
thingBuilder.withChannels(Arrays.asList( // assertThrows(IllegalArgumentException.class, () -> thingBuilder.withChannels(Arrays.asList( //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build(), //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build())));
}
@Test
public void testWithChannelsDuplicatesVararg() {
assertThrows(IllegalArgumentException.class, () -> thingBuilder.withChannels( //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build(), // ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build(), //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build())); ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build()));
} }
@Test(expected = IllegalArgumentException.class)
public void testWithChannelsDuplicatesVararg() {
thingBuilder.withChannels( //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build(), //
ChannelBuilder.create(new ChannelUID(THING_UID, "channel1")).build());
}
@Test @Test
public void testWithoutChannel() { public void testWithoutChannel() {
thingBuilder.withChannels( // thingBuilder.withChannels( //
@ -108,10 +110,10 @@ public class ThingBuilderTest {
assertThat(thingBuilder.build().getChannels(), hasSize(2)); assertThat(thingBuilder.build().getChannels(), hasSize(2));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testWithChannelWrongThing() { public void testWithChannelWrongThing() {
thingBuilder.withChannel( assertThrows(IllegalArgumentException.class, () -> thingBuilder.withChannel(
ChannelBuilder.create(new ChannelUID(new ThingUID(THING_TYPE_UID, "wrong"), "channel1")).build()); ChannelBuilder.create(new ChannelUID(new ThingUID(THING_TYPE_UID, "wrong"), "channel1")).build()));
} }
@Test @Test

View File

@ -13,10 +13,10 @@
package org.openhab.core.thing.binding.builder; package org.openhab.core.thing.binding.builder;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingStatusInfo; import org.openhab.core.thing.ThingStatusInfo;
@ -30,7 +30,7 @@ public class ThingStatusInfoBuilderTest {
private ThingStatusInfoBuilder builder; private ThingStatusInfoBuilder builder;
@Before @BeforeEach
public void setup() { public void setup() {
builder = ThingStatusInfoBuilder.create(ThingStatus.ONLINE); builder = ThingStatusInfoBuilder.create(ThingStatus.ONLINE);
} }

View File

@ -13,14 +13,14 @@
package org.openhab.core.thing.dto; package org.openhab.core.thing.dto;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
import org.openhab.core.thing.Channel; import org.openhab.core.thing.Channel;

View File

@ -13,14 +13,14 @@
package org.openhab.core.thing.dto; package org.openhab.core.thing.dto;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Bridge;

View File

@ -13,14 +13,15 @@
package org.openhab.core.thing.firmware; package org.openhab.core.thing.firmware;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays; import java.util.Arrays;
import java.util.Set; import java.util.Set;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.events.Event; import org.openhab.core.events.Event;
import org.openhab.core.test.java.JavaTest; import org.openhab.core.test.java.JavaTest;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
@ -38,7 +39,7 @@ public class FirmwareEventFactoryTest extends JavaTest {
private FirmwareEventFactory eventFactory; private FirmwareEventFactory eventFactory;
@Before @BeforeEach
public void setUp() { public void setUp() {
eventFactory = new FirmwareEventFactory(); eventFactory = new FirmwareEventFactory();
} }
@ -50,24 +51,27 @@ public class FirmwareEventFactoryTest extends JavaTest {
FirmwareUpdateProgressInfoEvent.TYPE, FirmwareUpdateResultInfoEvent.TYPE)); FirmwareUpdateProgressInfoEvent.TYPE, FirmwareUpdateResultInfoEvent.TYPE));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateEventForUnknownType() throws Exception { public void testCreateEventForUnknownType() throws Exception {
eventFactory.createEventByType("unknownType", "topic", "somePayload", "Source"); assertThrows(IllegalArgumentException.class,
() -> eventFactory.createEventByType("unknownType", "topic", "somePayload", "Source"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNullStatusInfo() { public void testNullStatusInfo() {
FirmwareEventFactory.createFirmwareStatusInfoEvent(null); assertThrows(IllegalArgumentException.class, () -> FirmwareEventFactory.createFirmwareStatusInfoEvent(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNullUpdateProgressInfo() { public void testNullUpdateProgressInfo() {
FirmwareEventFactory.createFirmwareUpdateProgressInfoEvent(null); assertThrows(IllegalArgumentException.class,
() -> FirmwareEventFactory.createFirmwareUpdateProgressInfoEvent(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNullUpdateResultInfo() { public void testNullUpdateResultInfo() {
FirmwareEventFactory.createFirmwareUpdateResultInfoEvent(null); assertThrows(IllegalArgumentException.class,
() -> FirmwareEventFactory.createFirmwareUpdateResultInfoEvent(null));
} }
@Test @Test

View File

@ -12,10 +12,9 @@
*/ */
package org.openhab.core.thing.internal; package org.openhab.core.thing.internal;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -23,10 +22,14 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.events.Event; import org.openhab.core.events.Event;
import org.openhab.core.events.EventPublisher; import org.openhab.core.events.EventPublisher;
import org.openhab.core.items.GenericItem; import org.openhab.core.items.GenericItem;
@ -55,6 +58,8 @@ import org.openhab.core.thing.type.ChannelTypeRegistry;
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
* @author Kai Kreuzer - added tests with multiple links * @author Kai Kreuzer - added tests with multiple links
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class AutoUpdateManagerTest { public class AutoUpdateManagerTest {
private static final ThingUID THING_UID_ONLINE = new ThingUID("test::mock-online"); private static final ThingUID THING_UID_ONLINE = new ThingUID("test::mock-online");
@ -82,9 +87,8 @@ public class AutoUpdateManagerTest {
private AutoUpdateManager aum; private AutoUpdateManager aum;
private final Map<ChannelUID, AutoUpdatePolicy> policies = new HashMap<>(); private final Map<ChannelUID, AutoUpdatePolicy> policies = new HashMap<>();
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
event = ItemEventFactory.createCommandEvent("test", new StringType("AFTER")); event = ItemEventFactory.createCommandEvent("test", new StringType("AFTER"));
item = new StringItem("test"); item = new StringItem("test");
item.setState(new StringType("BEFORE")); item.setState(new StringType("BEFORE"));

View File

@ -14,7 +14,6 @@ package org.openhab.core.thing.internal;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
@ -25,9 +24,13 @@ import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNull;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.common.registry.ProviderChangeListener; import org.openhab.core.common.registry.ProviderChangeListener;
import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.LocaleProvider;
import org.openhab.core.items.Item; import org.openhab.core.items.Item;
@ -49,6 +52,8 @@ import org.openhab.core.thing.type.ChannelTypeRegistry;
/** /**
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
public class ChannelItemProviderTest { public class ChannelItemProviderTest {
private static final ChannelUID CHANNEL_UID = new ChannelUID("test:test:test:test"); private static final ChannelUID CHANNEL_UID = new ChannelUID("test:test:test:test");
@ -70,10 +75,8 @@ public class ChannelItemProviderTest {
private ChannelItemProvider provider; private ChannelItemProvider provider;
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
provider = createProvider(); provider = createProvider();
Map<String, Object> props = new HashMap<>(); Map<String, Object> props = new HashMap<>();

View File

@ -12,9 +12,9 @@
*/ */
package org.openhab.core.thing.internal; package org.openhab.core.thing.internal;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.library.CoreItemFactory; import org.openhab.core.library.CoreItemFactory;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;

View File

@ -12,15 +12,18 @@
*/ */
package org.openhab.core.thing.internal; package org.openhab.core.thing.internal;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.openhab.core.common.SafeCaller; import org.openhab.core.common.SafeCaller;
import org.openhab.core.config.core.ConfigDescriptionRegistry; import org.openhab.core.config.core.ConfigDescriptionRegistry;
import org.openhab.core.config.core.validation.ConfigDescriptionValidator; import org.openhab.core.config.core.validation.ConfigDescriptionValidator;
@ -43,6 +46,8 @@ import org.osgi.framework.Bundle;
/** /**
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault @NonNullByDefault
public class ThingManagerImplTest { public class ThingManagerImplTest {
@ -66,10 +71,8 @@ public class ThingManagerImplTest {
// This class is final so it cannot be mocked // This class is final so it cannot be mocked
private final ThingStatusInfoI18nLocalizationService thingStatusInfoI18nLocalizationService = new ThingStatusInfoI18nLocalizationService(); private final ThingStatusInfoI18nLocalizationService thingStatusInfoI18nLocalizationService = new ThingStatusInfoI18nLocalizationService();
@Before @BeforeEach
public void setup() { public void setup() {
initMocks(this);
when(bundleMock.getSymbolicName()).thenReturn("test"); when(bundleMock.getSymbolicName()).thenReturn("test");
when(bundleResolverMock.resolveBundle(any())).thenReturn(bundleMock); when(bundleResolverMock.resolveBundle(any())).thenReturn(bundleMock);
when(thingMock.getUID()).thenReturn(new ThingUID("test", "thing")); when(thingMock.getUID()).thenReturn(new ThingUID("test", "thing"));

View File

@ -13,7 +13,8 @@
package org.openhab.core.thing.internal.firmware; package org.openhab.core.thing.internal.firmware;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -22,8 +23,8 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.events.Event; import org.openhab.core.events.Event;
import org.openhab.core.events.EventPublisher; import org.openhab.core.events.EventPublisher;
import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.i18n.TranslationProvider;
@ -63,7 +64,7 @@ public final class ProgressCallbackTest {
private String cancelMessageKey = "update-canceled"; private String cancelMessageKey = "update-canceled";
private String usedMessagedKey; private String usedMessagedKey;
@Before @BeforeEach
public void setUp() { public void setUp() {
ThingTypeUID thingType = new ThingTypeUID("thing:type"); ThingTypeUID thingType = new ThingTypeUID("thing:type");
expectedThingUID = new ThingUID(thingType, "thingid"); expectedThingUID = new ThingUID(thingType, "thingid");
@ -103,31 +104,31 @@ public final class ProgressCallbackTest {
expectedThingUID, expectedFirmware, null); expectedThingUID, expectedFirmware, null);
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatUpdateThrowsIllegalStateExceptionIfUpdateIsFinished() { public void assertThatUpdateThrowsIllegalStateExceptionIfUpdateIsFinished() {
sut.defineSequence(ProgressStep.DOWNLOADING); sut.defineSequence(ProgressStep.DOWNLOADING);
sut.next(); sut.next();
sut.success(); sut.success();
assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS); assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS);
sut.update(100); assertThrows(IllegalStateException.class, () -> sut.update(100));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatDefineSequenceThrowsIllegalArguumentExceptionIfSequenceIsEmpty() { public void assertThatDefineSequenceThrowsIllegalArguumentExceptionIfSequenceIsEmpty() {
sut.defineSequence(); assertThrows(IllegalArgumentException.class, () -> sut.defineSequence());
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatSuccessThrowsIllegalStateExceptionIfProgressIsNotAt100Percent() { public void assertThatSuccessThrowsIllegalStateExceptionIfProgressIsNotAt100Percent() {
sut.update(99); sut.update(99);
sut.success(); assertThrows(IllegalStateException.class, () -> sut.success());
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatSuccessThrowsIllegalStateExceptionIfLastProgressStepIsNotReached() { public void assertThatSuccessThrowsIllegalStateExceptionIfLastProgressStepIsNotReached() {
sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING); sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING);
sut.next(); sut.next();
sut.success(); assertThrows(IllegalStateException.class, () -> sut.success());
} }
@Test @Test
@ -138,20 +139,20 @@ public final class ProgressCallbackTest {
sut.success(); sut.success();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUpdateThrowsIllegalArgumentExceptionIfProgressSmaller0() { public void assertThatUpdateThrowsIllegalArgumentExceptionIfProgressSmaller0() {
sut.update(-1); assertThrows(IllegalArgumentException.class, () -> sut.update(-1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUpdateThrowsIllegalArgumentExceptionIfProgressGreater100() { public void assertThatUpdateThrowsIllegalArgumentExceptionIfProgressGreater100() {
sut.update(101); assertThrows(IllegalArgumentException.class, () -> sut.update(101));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatUpdateThrowsIllegalArgumentExceptionIfNewProgressIsSmallerThanOldProgress() { public void assertThatUpdateThrowsIllegalArgumentExceptionIfNewProgressIsSmallerThanOldProgress() {
sut.update(10); sut.update(10);
sut.update(9); assertThrows(IllegalArgumentException.class, () -> sut.update(9));
} }
@Test @Test
@ -239,14 +240,14 @@ public final class ProgressCallbackTest {
assertThat(postedEvents.size(), is(8)); assertThat(postedEvents.size(), is(8));
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatCancelThrowsIllegalStateExceptionIfUpdateIsFinished() { public void assertThatCancelThrowsIllegalStateExceptionIfUpdateIsFinished() {
sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING); sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING);
sut.next(); sut.next();
sut.next(); sut.next();
sut.success(); sut.success();
assertThatUpdateResultEventIsValid(postedEvents.get(2), null, FirmwareUpdateResult.SUCCESS); assertThatUpdateResultEventIsValid(postedEvents.get(2), null, FirmwareUpdateResult.SUCCESS);
sut.canceled(); assertThrows(IllegalStateException.class, () -> sut.canceled());
} }
@Test @Test
@ -287,9 +288,9 @@ public final class ProgressCallbackTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void assertThatPendingThrowsIllegalArgumentExceptionIfStepSequenceIsNotDefinedAndNoProgressWasSet() { public void assertThatPendingThrowsIllegalArgumentExceptionIfStepSequenceIsNotDefinedAndNoProgressWasSet() {
sut.pending(); assertThrows(IllegalArgumentException.class, () -> sut.pending());
} }
@Test @Test
@ -305,40 +306,40 @@ public final class ProgressCallbackTest {
assertThatUpdateResultEventIsValid(postedEvents.get(0), cancelMessageKey, FirmwareUpdateResult.CANCELED); assertThatUpdateResultEventIsValid(postedEvents.get(0), cancelMessageKey, FirmwareUpdateResult.CANCELED);
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatFailedThrowsIllegalStateExceptionIfItsCalledMultipleTimes() { public void assertThatFailedThrowsIllegalStateExceptionIfItsCalledMultipleTimes() {
sut.failed("DummyMessageKey"); sut.failed("DummyMessageKey");
sut.failed("DummyMessageKey"); assertThrows(IllegalStateException.class, () -> sut.failed("DummyMessageKey"));
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatFailedThrowsIllegalStateExceptionForSuccessfulUpdates() { public void assertThatFailedThrowsIllegalStateExceptionForSuccessfulUpdates() {
sut.update(100); sut.update(100);
sut.success(); sut.success();
assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS); assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS);
sut.failed("DummyMessageKey"); assertThrows(IllegalStateException.class, () -> sut.failed("DummyMessageKey"));
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatSuccessThrowsIllegalStateExceptionIfItsCalledMultipleTimes() { public void assertThatSuccessThrowsIllegalStateExceptionIfItsCalledMultipleTimes() {
sut.update(100); sut.update(100);
sut.success(); sut.success();
assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS); assertThatUpdateResultEventIsValid(postedEvents.get(1), null, FirmwareUpdateResult.SUCCESS);
sut.success(); assertThrows(IllegalStateException.class, () -> sut.success());
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatPendingThrowsIllegalStateExceptionIfUpdateFailed() { public void assertThatPendingThrowsIllegalStateExceptionIfUpdateFailed() {
sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING); sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING);
sut.failed("DummyMessageKey"); sut.failed("DummyMessageKey");
sut.pending(); assertThrows(IllegalStateException.class, () -> sut.pending());
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatNextThrowsIllegalStateExceptionIfUpdateIsNotPendingAndNoFurtherStepsAvailable() { public void assertThatNextThrowsIllegalStateExceptionIfUpdateIsNotPendingAndNoFurtherStepsAvailable() {
sut.defineSequence(ProgressStep.DOWNLOADING); sut.defineSequence(ProgressStep.DOWNLOADING);
sut.next(); sut.next();
sut.next(); assertThrows(IllegalStateException.class, () -> sut.next());
} }
@Test @Test
@ -350,13 +351,13 @@ public final class ProgressCallbackTest {
assertThat(sut.getCurrentStep(), is(ProgressStep.DOWNLOADING)); assertThat(sut.getCurrentStep(), is(ProgressStep.DOWNLOADING));
} }
@Test(expected = IllegalStateException.class) @Test
public void assertThatPendingThrowsIllegalStateExceptionIfUpdateWasSuccessful() { public void assertThatPendingThrowsIllegalStateExceptionIfUpdateWasSuccessful() {
sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING); sut.defineSequence(ProgressStep.DOWNLOADING, ProgressStep.TRANSFERRING);
sut.next(); sut.next();
sut.next(); sut.next();
sut.success(); sut.success();
sut.pending(); assertThrows(IllegalStateException.class, () -> sut.pending());
} }
private void assertThatProgressInfoEventIsValid(Event event, ProgressStep expectedStep, boolean expectedPending, private void assertThatProgressInfoEventIsValid(Event event, ProgressStep expectedStep, boolean expectedPending,

View File

@ -15,8 +15,8 @@ package org.openhab.core.thing.internal.profiles;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.CommonTriggerEvents; import org.openhab.core.thing.CommonTriggerEvents;
@ -31,10 +31,9 @@ import org.openhab.core.types.Command;
*/ */
public class RawButtonOnOffSwitchProfileTest { public class RawButtonOnOffSwitchProfileTest {
@Mock private @Mock ProfileCallback mockCallback;
private ProfileCallback mockCallback;
@Before @BeforeEach
public void setup() { public void setup() {
mockCallback = mock(ProfileCallback.class); mockCallback = mock(ProfileCallback.class);
} }

View File

@ -15,8 +15,8 @@ package org.openhab.core.thing.internal.profiles;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.openhab.core.library.types.HSBType; import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
@ -34,10 +34,9 @@ import org.openhab.core.types.UnDefType;
*/ */
public class RawButtonToggleSwitchProfileTest { public class RawButtonToggleSwitchProfileTest {
@Mock private @Mock ProfileCallback mockCallback;
private ProfileCallback mockCallback;
@Before @BeforeEach
public void setup() { public void setup() {
mockCallback = mock(ProfileCallback.class); mockCallback = mock(ProfileCallback.class);
} }

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.core.thing.internal.profiles; package org.openhab.core.thing.internal.profiles;
import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.profiles.ProfileCallback; import org.openhab.core.thing.profiles.ProfileCallback;
@ -26,15 +26,10 @@ import org.openhab.core.thing.profiles.ProfileCallback;
* *
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class SystemDefaultProfileTest { public class SystemDefaultProfileTest {
@Mock private @Mock ProfileCallback mockCallback;
private ProfileCallback mockCallback;
@Before
public void setup() {
initMocks(this);
}
@Test @Test
public void testOnCommand() { public void testOnCommand() {

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.core.thing.internal.profiles; package org.openhab.core.thing.internal.profiles;
import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.profiles.ProfileCallback; import org.openhab.core.thing.profiles.ProfileCallback;
@ -26,15 +26,10 @@ import org.openhab.core.thing.profiles.ProfileCallback;
* *
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
*/ */
@ExtendWith(MockitoExtension.class)
public class SystemFollowProfileTest { public class SystemFollowProfileTest {
@Mock private @Mock ProfileCallback mockCallback;
private ProfileCallback mockCallback;
@Before
public void setup() {
initMocks(this);
}
@Test @Test
public void testOnCommand() { public void testOnCommand() {

View File

@ -13,15 +13,16 @@
package org.openhab.core.thing.internal.profiles; package org.openhab.core.thing.internal.profiles;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.number.IsCloseTo.closeTo; import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import javax.measure.Unit; import javax.measure.Unit;
import javax.measure.quantity.Temperature; import javax.measure.quantity.Temperature;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.openhab.core.config.core.Configuration; import org.openhab.core.config.core.Configuration;
import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.DecimalType;
@ -40,7 +41,7 @@ import org.openhab.core.types.State;
*/ */
public class SystemOffsetProfileTest { public class SystemOffsetProfileTest {
@Before @BeforeEach
public void setup() { public void setup() {
// initialize parser with ImperialUnits, otherwise units like °F are unknown // initialize parser with ImperialUnits, otherwise units like °F are unknown
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.core.thing.internal.profiles; package org.openhab.core.thing.internal.profiles;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.openhab.core.library.types.DateTimeType; import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.DecimalType;

View File

@ -12,14 +12,14 @@
*/ */
package org.openhab.core.thing.type; package org.openhab.core.thing.type;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests the {@link ChannelGroupTypeBuilder}. * Tests the {@link ChannelGroupTypeBuilder}.
@ -36,15 +36,16 @@ public class ChannelGroupTypeBuilderTest {
private ChannelGroupTypeBuilder builder; private ChannelGroupTypeBuilder builder;
@Before @BeforeEach
public void setup() { public void setup() {
// set up a valid basic ChannelGroupTypeBuilder // set up a valid basic ChannelGroupTypeBuilder
builder = ChannelGroupTypeBuilder.instance(CHANNEL_GROUP_TYPE_UID, LABEL); builder = ChannelGroupTypeBuilder.instance(CHANNEL_GROUP_TYPE_UID, LABEL);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenLabelIsBlankForStateShouldFail() { public void whenLabelIsBlankForStateShouldFail() {
ChannelGroupTypeBuilder.instance(CHANNEL_GROUP_TYPE_UID, ""); assertThrows(IllegalArgumentException.class,
() -> ChannelGroupTypeBuilder.instance(CHANNEL_GROUP_TYPE_UID, ""));
} }
@Test @Test

View File

@ -13,8 +13,9 @@
package org.openhab.core.thing.type; package org.openhab.core.thing.type;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.net.URI; import java.net.URI;
@ -22,8 +23,8 @@ import java.net.URISyntaxException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.thing.CommonTriggerEvents; import org.openhab.core.thing.CommonTriggerEvents;
import org.openhab.core.types.EventDescription; import org.openhab.core.types.EventDescription;
import org.openhab.core.types.EventOption; import org.openhab.core.types.EventOption;
@ -57,7 +58,7 @@ public class ChannelTypeBuilderTest {
private StateChannelTypeBuilder stateBuilder; private StateChannelTypeBuilder stateBuilder;
private TriggerChannelTypeBuilder triggerBuilder; private TriggerChannelTypeBuilder triggerBuilder;
@Before @BeforeEach
public void setup() throws URISyntaxException { public void setup() throws URISyntaxException {
configDescriptionUri = new URI("config:dummy"); configDescriptionUri = new URI("config:dummy");
// set up a valid basic ChannelTypeBuilder // set up a valid basic ChannelTypeBuilder
@ -65,19 +66,19 @@ public class ChannelTypeBuilderTest {
triggerBuilder = ChannelTypeBuilder.trigger(CHANNEL_TYPE_UID, LABEL); triggerBuilder = ChannelTypeBuilder.trigger(CHANNEL_TYPE_UID, LABEL);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenLabelIsBlankForStateShouldFail() { public void whenLabelIsBlankForStateShouldFail() {
ChannelTypeBuilder.state(CHANNEL_TYPE_UID, "", ITEM_TYPE); assertThrows(IllegalArgumentException.class, () -> ChannelTypeBuilder.state(CHANNEL_TYPE_UID, "", ITEM_TYPE));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenItemTypeIsBlankForStateShouldFail() { public void whenItemTypeIsBlankForStateShouldFail() {
ChannelTypeBuilder.state(CHANNEL_TYPE_UID, LABEL, ""); assertThrows(IllegalArgumentException.class, () -> ChannelTypeBuilder.state(CHANNEL_TYPE_UID, LABEL, ""));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenLabelIsBlankForTriggerShouldFail() { public void whenLabelIsBlankForTriggerShouldFail() {
ChannelTypeBuilder.trigger(CHANNEL_TYPE_UID, ""); assertThrows(IllegalArgumentException.class, () -> ChannelTypeBuilder.trigger(CHANNEL_TYPE_UID, ""));
} }
@Test @Test

View File

@ -13,8 +13,9 @@
package org.openhab.core.thing.type; package org.openhab.core.thing.type;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import java.net.URI; import java.net.URI;
@ -25,8 +26,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
/** /**
@ -47,30 +48,31 @@ public class ThingTypeBuilderTest {
private @NonNullByDefault({}) ThingTypeBuilder builder; private @NonNullByDefault({}) ThingTypeBuilder builder;
@Before @BeforeEach
public void setup() { public void setup() {
// set up a valid basic ThingTypeBuilder // set up a valid basic ThingTypeBuilder
builder = ThingTypeBuilder.instance(BINDING_ID, THING_TYPE_ID, LABEL); builder = ThingTypeBuilder.instance(BINDING_ID, THING_TYPE_ID, LABEL);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenThingTypeIdAndBindingIdBlankShouldFail() { public void whenThingTypeIdAndBindingIdBlankShouldFail() {
ThingTypeBuilder.instance("", "", LABEL).build(); assertThrows(IllegalArgumentException.class, () -> ThingTypeBuilder.instance("", "", LABEL).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenThingTypeIdBlankShouldFail() { public void whenThingTypeIdBlankShouldFail() {
ThingTypeBuilder.instance(BINDING_ID, "", LABEL).build(); assertThrows(IllegalArgumentException.class, () -> ThingTypeBuilder.instance(BINDING_ID, "", LABEL).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenBindingIdBlankShouldFail() { public void whenBindingIdBlankShouldFail() {
ThingTypeBuilder.instance("", THING_TYPE_ID, LABEL).build(); assertThrows(IllegalArgumentException.class, () -> ThingTypeBuilder.instance("", THING_TYPE_ID, LABEL).build());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void whenLabelBlankShouldFail() { public void whenLabelBlankShouldFail() {
ThingTypeBuilder.instance(THING_TYPE_ID, BINDING_ID, "").build(); assertThrows(IllegalArgumentException.class,
() -> ThingTypeBuilder.instance(THING_TYPE_ID, BINDING_ID, "").build());
} }
@Test @Test

View File

@ -13,17 +13,16 @@
package org.openhab.core.thing.util; package org.openhab.core.thing.util;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.openhab.core.thing.binding.builder.ThingStatusInfoBuilder.create; import static org.openhab.core.thing.binding.builder.ThingStatusInfoBuilder.create;
import static org.openhab.core.thing.util.ThingHandlerHelper.isHandlerInitialized; import static org.openhab.core.thing.util.ThingHandlerHelper.isHandlerInitialized;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Rule; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit; import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.MockitoRule;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
@ -37,15 +36,14 @@ import org.openhab.core.thing.binding.builder.ThingBuilder;
* @author Simon Kaufmann - Initial contribution * @author Simon Kaufmann - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java * @author Wouter Born - Migrate tests from Groovy to Java
*/ */
@ExtendWith(MockitoExtension.class)
public class ThingHandlerHelperTest { public class ThingHandlerHelperTest {
private Thing thing; private Thing thing;
private @Mock ThingHandler thingHandler; private @Mock ThingHandler thingHandler;
public @Rule MockitoRule rule = MockitoJUnit.rule(); @BeforeEach
@Before
public void setup() { public void setup() {
thing = ThingBuilder.create(new ThingTypeUID("test:test"), new ThingUID("test:test:test")).build(); thing = ThingBuilder.create(new ThingTypeUID("test:test"), new ThingUID("test:test:test")).build();
} }

Some files were not shown because too many files have changed in this diff Show More