Вопрос

In my Java class I have a method that creates an object and implements certain logic to assign random values to some of its variables, using one static instance of Random (static Random rn = new Random();). One of these variables is objectId.

How can I write Spock unit test to verify that objectId value is unique among all created objects?

If I needed it just for two consecutive objects I would write something like this (omitting imports):

class MyTest extends Specification {

    def @Shared obj = new MyObject()

    def "consecutive IDs are not equal"() {
        given:
            def id1 = ar.randomObject(MyObject.rn).getId()
            def id2 = ar.randomObject(MyObject.rn).getId()
        expect:
            id1 != id2

    }
} 

How to extend this logic to a variable number of instances?

Это было полезно?

Решение

How about this? Given a test class:

class Test {
    static Random r = new Random()
    Long objectId = r.nextLong()
}

//Test Case
def "consecutive IDs are not equal"() {
    given: "20 ids from 20 Test Objects"
        def ids = (1..20).collect { new Test().objectId }

    expect: "ids are unique"
        // use unique(false) not to mutate the list
        ids.unique(false) == ids
}

Другие советы

I'm afraid my groovy isn't up to the task, but the logic is:

def ids as Set

def "IDs are not duplicated"() {
  expect:
    ids.contains(id) == false

  cleanup:
    ids.add(id)

  where:
    id << listOfAllIds()
}

That is: assert that each id isn't currently known. When the assertion doesn't fail, record the id as currently known.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top