File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed
commonMain/kotlin/assertk/assertions
commonTest/kotlin/test/assertk/assertions Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -178,6 +178,34 @@ fun Assert<Array<*>>.containsExactly(vararg elements: Any?) = given { actual ->
178178 expectedListDiff(elements.asList(), actual.asList())
179179}
180180
181+ /* *
182+ * Asserts the collection contains at least one instance of a given type.
183+ *
184+ * ```
185+ * assertThat(arrayOf<Any>("one", "two", 1)).containsInstanceOf<String>().each {
186+ * it.hasLength(3)
187+ * }
188+ * ```
189+ */
190+ inline fun <reified T > Assert <Array <* >>.containsInstanceOf (): Assert <List <T >> {
191+ return transform(" contains subtype of ${T ::class } " ) { actual ->
192+ actual.filterIsInstance<T >().also {
193+ if (it.isEmpty()) expected(" to contain at least one instance of ${T ::class } but was ${actual.asList()} " )
194+ }
195+ }
196+ }
197+
198+ /* *
199+ * Asserts the collection does not contain an instance of a given type.
200+ *
201+ * ```
202+ * assertThat(arrayOf<Any>("one", "two", 1)).doesNotContainInstanceOf<Double>()
203+ * ```
204+ */
205+ inline fun <reified T > Assert <Array <* >>.doesNotContainInstanceOf () = given { actual ->
206+ if (actual.any { it is T }) expected(" to not contain instances of ${T ::class } but was ${actual.asList()} " )
207+ }
208+
181209/* *
182210 * Asserts on each item in the array. The given lambda will be run for each item.
183211 *
Original file line number Diff line number Diff line change @@ -322,6 +322,32 @@ class ArrayTest {
322322 }
323323 // endregion
324324
325+ // region containsInstanceOf
326+ @Test fun containsInstanceOf_element_present_passes () {
327+ assertThat(arrayOf<Any >(1 , " two" )).containsInstanceOf<String >().single().isEqualTo(" two" )
328+ }
329+
330+ @Test fun containsInstanceOf_element_missing_fails () {
331+ val error = assertFailsWith<AssertionError > {
332+ assertThat(arrayOf<Any >(1 , " two" )).containsInstanceOf<Double >()
333+ }
334+ assertEquals(" expected to contain at least one instance of class kotlin.Double but was [1, two]" , error.message)
335+ }
336+ // endregion
337+
338+ // region doesNotContainInstanceOf
339+ @Test fun doesNotContainInstanceOf_element_present_fails () {
340+ val error = assertFailsWith<AssertionError >() {
341+ assertThat(arrayOf<Any >(1 , " two" )).doesNotContainInstanceOf<String >()
342+ }
343+ assertEquals(" expected to not contain instances of class kotlin.String but was [1, two]" , error.message)
344+ }
345+
346+ @Test fun doesNotContainInstanceOf_element_missing_passes () {
347+ assertThat(arrayOf<Any >(1 , " two" )).doesNotContainInstanceOf<Double >()
348+ }
349+ // endregion
350+
325351 // region each
326352 @Test
327353 fun each_empty_list_passes () {
You can’t perform that action at this time.
0 commit comments