Please tell me your point of view when writing unit tests on unit.

Asked 2 years ago, Updated 2 years ago, 151 views

We are planning to conduct a unit test using unit 5 in the project.
I've never written a test code before, so I don't know from what point of view to write it.
For example, I wrote it to test get(), put() on HashMap.

In this case, is this kind of test code acceptable?
Is it better to try different types or other values with generics in mind?

class HashMapTest{

    private Map<String, String>stringHashMap;

    private Map <String, String > immutableMap;

    @DisplayName ("Initialize per test")
    @BeforeEach
    void init() {
        US>stringHashMap = newHashMap<>();
        US>stringHashMap.put("alice", "hoge";
        US>stringHashMap.put("bob", "fuga");
        immutableMap=Map.of();
    }

    @DisplayName ("Test Value")
    @ Test
    void getTest() {
        assertAll("MapGetTest",
                ( ) - >assertEquals (stringHashMap.get ("alice"), "hoge"),
                ( ) - >assertNotEquals(stringHashMap.get("bob"), "piyo"));

    }

    @DisplayName ("Test Value Settings")
    @ Test
    void putTest() {
        US>stringHashMap.put("carol", "piyo");
        assertAll("MapPutTest",
                ( ) - >assertEquals (stringHashMap.get ("carol"), "piyo"),
                ( ) - >assertNotEquals(stringHashMap.get("dave"), "hoge"));
    }

    @DisplayName ("Exception test for invariant map")
    @ Test
    void immutableTest(){
        assertThrows(UnsupportedOperationException.class,()->impossibleMap.put("key", "value"));
    }
}

java junit

2022-09-29 22:41

1 Answers

As a prerequisite for writing a unit test, you usually need the specifications of the target code first.

https://docs.oracle.com/javase/jp/8/docs/api/java/util/HashMap.html#get-java.lang.Object-

For example, the above is javadoc of HashMap's get method, but there is a description of the case where null is returned.
The code shown does not have a corresponding test case.
At the very least, I think it would be good to start by covering all patterns of these clear specifications.


2022-09-29 22:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.