Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit how to check if string is equal to one of two strings?

Tags:

This seems like a super simple question, but I just cannot figure it out.

I'm just trying to assert that a string is equal to "string1" OR "string2".

Here's what I've tried, but neither obviously doesn't work.

assertEquals(d.getFormType(), "string1") || assertEquals(d.getFormType(), "string2");

assertEquals(d.getFormType(), "string1" || "string2");
like image 830
Catfish Avatar asked Oct 04 '12 14:10

Catfish


3 Answers

I recommend you use Hamcrest matchers. They are integrated into JUnit via assertThat(), but you'll need to download and install hamcrest-all.jar too.

Using Hamcrest, you could solve your problem like this:

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

assertThat(d.getFormType(), isOneOf("string1", "string2"));

Another alternative, if you can't install Hamcrest, would be to use a regular expression:

assertTrue(d.getFormType().matches("(string1|string2)"));

This is shorter, and arguably more readable, than combining two equals() statements:

String actual = d.getFormType();
assertTrue("string1".equals(actual) || "string2".equals(actual));
like image 105
ᴇʟᴇvᴀтᴇ Avatar answered Oct 23 '22 07:10

ᴇʟᴇvᴀтᴇ


You could use assertTrue():

assertTrue(d.getFormType().equals("string1") ||
           d.getFormType().equals("string2"));

or use the extended version to provide more information in the event of failure:

assertTrue("Unexpected value for d.getFormType(): " + d.getFormType(),
           d.getFormType().equals("string1") ||
           d.getFormType().equals("string2"));
like image 21
hmjd Avatar answered Oct 23 '22 07:10

hmjd


The assertion class doesn't have a direct way to do what you want. But you can always fall back to assertTrue and check any condition you want.

assertTrue("string1".equals(d.getFormType()) || "string2".equals(d.getFormType()))
like image 31
Martin Serrano Avatar answered Oct 23 '22 07:10

Martin Serrano