Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert an actual value against 2 or more expected values?

I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

like image 588
Alex Avatar asked May 17 '11 09:05

Alex


People also ask

Which assertion should you use to compare an expected value to an actual value?

You are correct with your expected & actual understanding. int x=1+2; assertEquals(x,2);

Which method is used to check actual and expected values are equal or not?

assertEquals() is a method that takes a minimum of 2 arguments and compares actual results with expected results. If both match, then the assertion is passed and the test case is marked as passed.

How do you assert multiple values in testNG?

Selenium doesn't support any kind of the assertion, you have go with the frameworks ex: testNG , JUnit ... I can suggest you 2 methods for asserting multiple values using testNG by assuming you have stored multiple values in ArrayList . You may have to change the logic little based on the data structure you are using.

How do you assert two values in Java?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).


2 Answers

Using the Hamcrest CoreMatcher (included in JUnit 4.4 and later) and assertThat():

assertThat(myString, anyOf(is("value1"), is("value2"))); 
like image 196
Joachim Sauer Avatar answered Sep 18 '22 11:09

Joachim Sauer


I would use AssertJ for this:

import static org.assertj.core.api.Assertions.*;  assertThat("hello").isIn("hello", "world"); 

It's more concise and it will give you a descriptive message when the assertion fails.

like image 32
Jonathan Avatar answered Sep 19 '22 11:09

Jonathan