简体   繁体   中英

About unit-test dependency

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?

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.

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.
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM