Unit testing Java application with Mockito/JUnit-Database operations

喜夏-厌秋 提交于 2019-12-23 04:54:23

问题


I am just beginner for implementing JUnit testing. I have a test case as given below. I have tried the when...thenreturn + verify method as well.

@RunWith(MockitoJUnitRunner.class)
public class CategoryControllerTest {

    @InjectMocks
    CategoryController categeoryCntrlr;
    @Mock
    private CategoryService catSvc;
    //private CategoryController catCntrl;

    @Test
    public void insertCategoryTest(){
        Category cat=new Category();
        cat.setStrCatName("Vehicle");
        String str = categeoryCntrlr.insertCategory(cat);
        System.out.println(str);
        assertEquals("failure",str);
    }
}

My Controller returns actually string 'success' but my above test case always says value of str as null.

When I used when...thenreturn() and verify, it is not actually testing my repository method, even if I change the return to something else the test case is passing. I know there is behavioral and testing. Is there any solution we can have both together? Can I get some beginners tutorial(I saw the calculator example and find methods tested, but no insert/update database)? I am not able to understand the reference document of Mockito, how it actually testing. Can anyone help me please ?


回答1:


I'm not 100% sure what your goals are for insertCategoryTest(), but you probably want to stub methods in your controller and/or service.

For example, to stub the insertCategory() method in your controller to always return "failure", you'd do the following:

when(categeoryCntrlr.insertCategory(any())).thenReturn("failure");

There are more examples about verifying interactions and stubbing method calls here: http://mockito.org

Link to Javadoc:

http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html



来源:https://stackoverflow.com/questions/37911776/unit-testing-java-application-with-mockito-junit-database-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!