I am trying to test a class in Java with spock. I am very new to it.
public class VerifyUser {
private final ServiceFacade serviceFacade;
//here is constructor
@RequestMapping(name = "verifyUser",
path = "/verifyuser",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<VerifyUserResponse> verifyUser(@RequestBody VerifyUserRequest request) {
serviceFacade.getRiskProfile(user.userId.id)
.flatMap(ServiceFacade.RiskProfile::getAffordabilityCheck)
.ifPresent(ac -> {
String rg = ac.getRiskGroup().name();
VerifyUserResponse.VerifyUserResponseBuilder vur = VerifyUserResponse.builder();
vur.attributes.put("RiskGroup", rg);
});
Now I should test this class and see what happens if the riskProfile
that I am getting is there.
I have started with something like this:
def "should verify user"() {
given:
def userId = "12345"
when:
def res = mvc.perform(post(url)
.content(json)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn()
.response
then: 1 * serviceFacade.getRiskProfile(user.userId.id) >> new ServiceFacade.RiskProfile("userId", 0, Instant.now(), Optional.empty(), Optional.empty())
RiskProfile.java class looks like this:
public class RiskProfile {
public final UserId userId;
public final long version;
public final Instant created;
public final Optional<Instant> lastUpdated;
public final Optional<AffordabilityCheck> affordabilityCheck;
public RiskProfile(UserId userId, long version, Instant created, Optional<Instant> lastUpdated,
Optional<AffordabilityCheck> affordabilityCheck) {
Validation.notNull(userId, "userId can not be null");
Validation.notNull(created, "created can not be null");
Validation.notNull(lastUpdated, "lastUpdated can not be null");
Validation.notNull(affordabilityCheck, "affordabilityCheck can not be null");
this.userId = userId;
this.version = version;
this.created = created;
this.lastUpdated = lastUpdated;
this.affordabilityCheck = affordabilityCheck;
}
public static RiskProfile create(UserId userId) {
return new RiskProfile(userId, 0, Instant.now(), Optional.empty(), Optional.empty());
}
public static RiskProfile create(UserId userId, Optional<AffordabilityCheck> affordabilityCheck) {
return new RiskProfile(userId, 0, Instant.now(), Optional.empty(), affordabilityCheck);
}
When I try to run my test I get:
Could not find matching constructor for: com.example.ServiceFacade$RiskProfile(String, String, Optional)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.example.ServiceFacade$RiskProfile(String, String, Optional)
You are invoking the following:
new ServiceFacade.RiskProfile("userId", 0, Instant.now(), Optional.empty(), Optional.empty())
The first argument to the RiskProfile
constructor needs to be a UserId
, not a String
.