Home > Software engineering >  How can i access an element from a list in AssertJ?
How can i access an element from a list in AssertJ?

Time:10-10

assertThat(service.load(1, setup.getEntity(), "OBJECT1").getImages().get(0).isSwitchedOn()).isEqualTo(false);

I'm accesing the unique element of the list in this way,but i'm wondering if there's a more appropriate way to do it.

CodePudding user response:

I think , service.load(1, setup.getEntity(), "OBJECT1") returns list of images.

If you want to check the first element in the list of images for isSwitchedOn, the asset that statement is fine.

In case if you want to assert all the images -> isSwitchedOn, better use loop and use assertThat.

CodePudding user response:

There are a method called singleElement() that can assert if a collection contain only one element.

There are also another method called extracting() which allow you to extract a property from an object for assertion.

Combing them will give you :

assertThat(list).singleElement().extracting(Image::isSwitchOn).isEqualTo(false);

Notice that extracting() will return you a generic object type for further chaining the assertion . If you want it to return a more specified boolean type , you can consider to use :

assertThat(list).singleElement().extracting(Image::isSwitchOn, as(BOOLEAN)).isFalse();

Or

assertThat(list).singleElement().extracting(Image::isSwitchOn).asInstanceOf(BOOLEAN).isFalse();

BOOLEAN is the static import from the class InstanceOfAssertFactories

CodePudding user response:

how about use public func? make it as a static func and put it in your tool-class.But if you just have one element,why not other structs?

  • Related