Search code examples
kotlinunit-testing

Chain assertions together in kotlin


I have an operation that I want to succeed with two different conditions. For example, if the status code is 501 OR message is not 'FAILED'. Is there a way to have assertions grouped together logically like AND/OR. If assertion 1 passes OR assertion 2 passes, I want my test case to succeed.


Solution

  • @cactustictacs suggests "naming" your assertions and then chaining them.

    I'll suggest an answer by showing code that validates 4x REST interface inputs that have some complex permutations that allowed / not allowed. This code is arguably easier to read than a classic if ... else structure.

    See how they are evaluated using the when construct. Perhaps you can take these ideas for your assertions...

    val userIdNotNull = userId != null
            && channelType == null
            && primaryMentorId == null
            && primaryClinicianId == null
    
    val userIdAndChannelTypeNotNull = userId != null
            && channelType != null
            && primaryMentorId == null
            && primaryClinicianId == null
    
    val primaryMentorIdNotNull = userId == null
            && channelType == null
            && primaryMentorId != null
            && primaryClinicianId == null
    
    val primaryClinicianIdNotNull = userId == null
            && channelType == null
            && primaryMentorId == null
            && primaryClinicianId != null
    
    val channels = when {
        userIdNotNull -> getChannelsByUserId(userId)
        userIdAndChannelTypeNotNull -> channelRepository.findByMemberIdAndChannelType(userId!!, channelType!!)
            .ifEmpty { throw NotFoundException() }
    
        primaryMentorIdNotNull -> channelRepository.findByPrimaryMentorId(primaryMentorId)
            .ifEmpty { throw NotFoundException() }
    
        primaryClinicianIdNotNull -> channelRepository.findByPrimaryClinicianId(primaryClinicianId)
            .ifEmpty { throw NotFoundException() }
    
        else -> throw InvalidRequestParameterException("This combination of request parameters is not supported")
    }