Issue
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?
Solution
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.
}
}
Answered By - tgdavies
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.