K
K
KaminskyIlya2015-10-30 07:46:18
Unit testing
KaminskyIlya, 2015-10-30 07:46:18

How to test throwing an exception by a method that checks an internal property of an object, if it is also checked in the constructor?

Good afternoon!
I have a class whose constructor looks like this:

public ImageCutter(int width, int height, int sizing)
  {
    if (sizing != SIZE_CUT && sizing != SIZE_COVER && sizing != SIZE_CONTAIN)
      throw new IllegalArgumentException(String.format("Image sizing method = %d not implemented.", sizing));
      ...
  }

Note that valid values ​​for sizing are checked in the constructor.
There is a method that depends on sizing:
public ImageCopyRegion getCopyRegion(int imageWidth, int imageHeight)
  {
    switch(sizing)
    {
      case SIZE_CUT:
        return getCuttedImage(imageWidth, imageHeight);

      case SIZE_COVER:
        return getCoveredImage(imageWidth, imageHeight);

      case SIZE_CONTAIN:
        return getContainedImage(imageWidth, imageHeight);
    }
    //TODO: как это протестировать, при условии того, что конструктор обрубил это?
    throw new IllegalStateException(String.format("Image sizing method = %d not implemented", sizing));
  }

Question 1: How can I write a test for that method so that IllegalStateException is thrown on invalid sizing?
The problem is below:
@Test(expected = IllegalStateException.class)
public void testGetCopyRegion_ForInvalidSizing_MustExcept()
{
   ImageCutter cutter = new ImageCutter(0, 0, 100); // будет исключение IllegalArgumentException  здесь, а не ниже
   cutter.getCopyRegion(-1, 0); // ожидается исключение здесь
}

P/S
Interested in an elegant solution from experienced testers.
P/S
It is possible, of course, instead of "magic constants" to use enum. Then it will be impossible to specify invalid values.
Well, as an option. But still interested in the concept.
The path we have is some field of the object, the range of values ​​of which is checked in the constructor.
Question 2: Should this value be checked in other public methods that use it?
Question 3: if it is decided to perform checks in methods (duplicate for code fault tolerance), how then to test these methods for throwing the corresponding exception (after all, the constructor will not allow creating the "wrong" object)?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question