Using Mockito with TestNG

后端 未结 3 1161
陌清茗
陌清茗 2021-02-09 06:33

I took a working test written for JUnit using Mockito and tried to adapt it to work with TestNG but oddly using TestNG only one test will work.

I think it is somehow rel

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 07:32

    There is a difference in the behaviour of these frameworks:

    • JUnit creates a new instance of class for every of its test methods. This means that the fields are not shared between tests.
    • But TestNG creates only one object and thus the state in fields is shared between to @Tests

    For Mockito you need to init mocks before every test method so that the state is not shared between two @Tests in TestNG:

    @BeforeMethod
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    

    For JUnit it works out of box because 2nd @Test has its own fields and its own mocks.

提交回复
热议问题