In class, we’ve been going over unit testing utilizing the JUnit Java testing framework. In the process of this, I’ve come across a couple of issues regarding classes that increment a “key” attribute, that is an class where an attribute’s value is based on the amount of previously built instances of that class. When testing to see if the attribute is assigned correctly, it isn’t consistent because of the compiler optimizations that JUnit uses. Tests run in an order which is most efficient, so the number of instances of the class may be different depending on the order the compiler goes through the tests (from what I’ve heard, at least).
I wanted to research a bit more into JUnit’s capabilities to see if I could figure out a solution to this problem, although I’ve already submitted the assignment that is relevant to this predicament. I found this blog post / guide to JUnit from Baeldung that goes through additional features from what I’ve learned in class. Perhaps here I can get some ideas as to address this issue.
What I first found interesting in this guide was the @DisplayName and @Disabled annotations. This is actually incredibly helpful, specifically @Disabled. In the assignment, I found that there were tests that weren’t possible because the functionality was not added to the classes we were working with. As a way to address it, I simply did this:
@Test
void test() {
// Functionality has not been added!
assertTrue(true);
}
This obviously isn’t the best approach to testing. With the @Disabled annotation, you can make a much better implementation of this test.
@Disabled
@Test
void test() {
assertTrue(method());
}
This is a much better way of testing functionality that hasn’t been added yet.
With regards to the previous problem, I had considered having a @BeforeAll method to create a two instances of a class so that I know exactly what the keys for both instances should be (1 and 2). The problem is that if the constructor for the class isn’t set up correctly, this could result in an error. This isn’t that big of a deal for a small program, but I could imagine it’s not really best practice.
However, JUnit has an Assumptions feature. This means that the desired method will only continue if the assumption is true. With this, we could theoretically run an assumption in a @BeforeAll method, and if it passes the assumption, we create instances with keys that are more easily testable.
@BeforeAll
void setUp() {
assumeNoException(() -> new Obj());
Obj obj1 = new Obj();
Obj obj2 = new Obj();
}
This way, we don’t have to worry about the test class not running all the way through due to an exception, and it’s also fairly elegant. Reminds me of why I like to code.
From the blog CS@Worcester – V's CompSCi Blog by V and used with permission of the author. All other rights reserved by the author.


