0

I've setup a unit test for a Java application that calls a web service. This web service returns a JSON string. Let's assume the following samples

{
"id": 2,
"time": "1346",
"user": {
    "firstname": "foo",
    "lastname": "bar",
    "email": "foo@bar.com"
  }
}

class GetUserImpl implements GetUser {
  public String getUserDetails() {
    return new MyWebService().getUserDetaild(];
  }
}

class Example Test {
  @Test
  public testGetUserDetails() {
    assertEquals(new GetUserImpl().getUserDetails(), regex);
  }
}

How would I use junit to test the following:

  • Is the ID a number, I don't care what the value is as long as it's not null and equal to or greater than 0
  • Is the time a valid format, regardless of the value
  • Is the email a valid email format, regardless of the value
user316114
  • 803
  • 7
  • 18
  • I assume you own and not just use that web service, otherwise it wouldn't be your job to test the (hopefully stable) API. – beatngu13 Oct 22 '16 at 23:07
  • Correct, I own the web service. I guess another way to put it is this. I need to test the schema is as expected and a second test to make sure the format of the values are valid. – user316114 Oct 22 '16 at 23:36
  • I wouldnt use assertEquals here, but assertThat and probably a custom matcher. – GhostCat Oct 23 '16 at 17:29

1 Answers1

0

Personally, I would prefer to break up your conditions into 3 different Assert statements and possible even 3 different tests and not try no lump all three requirements into one regex:

public void userIDShouldBeNonNullPositiveInteger()
public void userTimeShouldHaveValidTimeFormat()
public void userEmailShouldHaveValidFormat()

Also, agree with @GhostCat, that one good way to write these 3 tests is to have customMatchers for each. So, you could do something like this for the first test above:

public class PositiveIntegerMatcher extends TypeSafeDiagnosingMatcher<Integer> {
   @Override
   protected boolean matchesSafely(String idStr, Description description) {
       if (StringUtils.isNumeric(idStr) && isPositive(idStr) {
           return true;
       } else {
           return false;
       }
   }

   @Override
   public void describeTo(Description description) {

   }
}

This is some example code. Note, that I am using the apache commons (3) library to make things easy on myself, and I have not completed all of the code for you.

By breaking up this test into three tests, you will make your code much more readable and your intention clearer.

aramcodez
  • 102
  • 1
  • 8