Home > Software design >  About unit-test dependency
About unit-test dependency

Time:09-10

I'm trying to code some basic unit-tests for a project I am currently working on where I have my service that has a method addPlaneModel to add a plane model (under the hood it adds a PlaneModel instance into a TreeMap and throws a custom exception if the TreeMap already contains the key).

I could write a test (for example shouldAddNewPlane_Succeed) to see if it's properly adding the PlaneModel but my problem comes if I wanted to create a test to see if the PlaneModel already existed (for example shouldAddNewPlane_ThrowExistingModelException because I should call addPlaneModel twice to make it throw the exception, but if shouldAddNewPlane_Succeed test doesn't run first, I don't really 'know' if that method works as it should.

I've read that unit-tests should be independant from each other but I can't really grasp how to do it in this case, do I necessarily have to run them in order?

CodePudding user response:

You should be creating a new instance of the class you are testing before each test.

So your test class will look like:

class MyTests {
  private MyService myService;

  @Before // junit 4, or @BeforeEach for junit 5
  public void setup() {
    myService = new MyService(... pass mocks of dependencies ...);
  }

  @Test
  public void aTest() {
    myService...
  }

  @Test
  public void aTest2() {
    myService... // this is a fresh instance of MyService, any changes to the
                 // state of the instance used in aTest() are gone.
  }
}

CodePudding user response:

If you want to execute some common code before running a test, you can use the @Before method annotation in JUnit. For instance:

@Before
public void init() {
    LOG.info("startup");
    list = new ArrayList<>(Arrays.asList("test1", "test2"));
}

This code will always execute before any other test that you run. This is useful to define a certain order for execution to your tests.

  • Related