Search code examples
spring-cloud-contract

Negative (database dependent) test cases in Spring Cloud Contract


I am writing spring contract for a simple API that receives account number and returns "good" response if this account exists in the database or "bad" response otherwise. How do i specify "bad" response in the contract if the request that causes "bad" responses has the same format as "good" request?

My Java classes:

@PostMapping("/postrequest")
public AccountDto postMethod(@RequestBody FindAccountRequest rq){
  return service.findAccountByNumber(rq);
}

public class FindAccountRequest {
    String accountNumber;
}

public class AccountDto {
  Integer balance;
  Integer errorCode;
}

Contracts:

Contract.make {
    request {
        description("Existing account — good response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ] )
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [balance: anyInteger()] )
    }
}

Contract.make {
    request {
        description("Nonexistent account — bad response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ])
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [errorCode: anyInteger()] )
    }
}

Request:

{
    accountNumber: "12345678901234567890"
}

Solution

  • Prepare two different account numbers one for the positive case and one for the negative one. Two different contracts