Unit testing for object immutability

前端 未结 6 2065

I want to make sure that a given group of objects is immutable.

I was thinking about something along the lines of:

  1. check if every field is private final
6条回答
  •  感情败类
    2021-02-13 21:40

    Pretty sure it is impossible. Consider this function:

    public void doSomething() {
        if (System.currentTimeMillis() % 100000 == 0) {
            this.innerMember.changeState();
        }
    }
    

    First, you won't be able to detect it by running every class function, as this function changes the state of object precisely only once in 100 seconds.

    Second, you won't be able to detect it by parsing code, as you do not know if changeState() function changes the state of innerMember or not.

提交回复
热议问题