user2611581
user2611581

Reputation: 166

Appending values in a string in java

I have a REST API test suite where certain URIs are used repeatedly. Thus, I created a separate class with public static final members. Something like:

  public class RestURI {
        public RestURI(){}
        public static final String getAllShipsURI = "/ship/manager/ships";
        public static final String getAllPortsURI = "/port/manager/ports";
    }

However, is there a way to deal with URIs like this:

/infrastructure/ships/docked/" + shipId + "/capacity

I am looking for a way such that I can declare the URL like above in the RestURI class and still specify values in the test when I use them.

Upvotes: 1

Views: 75

Answers (3)

David
David

Reputation: 2702

I've used ANTLR StringTemplate for exactly this on multiple occasions. The ability to have inline macro parsing and a little if..else logic in the templates is pretty powerful, and it maintains good readability.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

You can use a constant format, rather than a String and use a static getter:

public static String getShipUri(int shipId) {
    return String.format("/infrastructure/ships/docked/%d/capacity", shipId);
}

Upvotes: 3

tbsalling
tbsalling

Reputation: 4545

You could use String.format. Like this:

public class RestURI {
    public RestURI(){}
    public xxx() {
       int shipId = 219001000;
       ... String.format(dockedShipURIFormat, shipId) ...;
    }
    public static final String dockedShipURIFormat = "/infrastructure/ships/docked/%d/capacity";
}

Upvotes: 1

Related Questions