Unit testing for object immutability

前端 未结 6 2068

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:44

    You may want to check out this project:

    Mutability Detector

    This library attempts to analyse the bytecode of a particular class, to discover if it is immutable or not. It allows testing for this condition in a unit test, as demonstrated in a video available here. It is certainly not perfect (a String field will be considered mutable, and your array example is not handled well) but it's more sophisticated than what FindBugs offers (i.e. only checking that every field is final).

    Disclaimer: I wrote it ;-)

提交回复
热议问题