简体   繁体   English

使用Mockito / JUnit-Database操作进行Java应用程序的单元测试

[英]Unit testing Java application with Mockito/JUnit-Database operations

I am just beginner for implementing JUnit testing. 我只是实现JUnit测试的初学者。 I have a test case as given below. 我有一个测试案例,如下所示。 I have tried the when...thenreturn + verify method as well. 我也尝试了when ... thenturn + verify方法。

@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. 我的控制器实际上返回了字符串“成功”,但是我的上述测试用例始终将str的值表示为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. 当我使用when ... thenreturn()并进行验证时,即使我将返回值更改为测试用例通过的其他值,它实际上也不在测试我的存储库方法。 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. 我无法理解Mockito的参考文档以及它的实际测试方式。 Can anyone help me please ? 有人可以帮我吗?

I'm not 100% sure what your goals are for insertCategoryTest() , but you probably want to stub methods in your controller and/or service. 我不确定100%确定insertCategoryTest()目标是什么,但是您可能想在控制器和/或服务中添加方法。

For example, to stub the insertCategory() method in your controller to always return "failure" , you'd do the following: 例如,要将您的控制器中的insertCategory()方法存根以始终返回"failure" ,请执行以下操作:

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

There are more examples about verifying interactions and stubbing method calls here: http://mockito.org 这里有更多有关验证交互和存根方法调用的示例: http : //mockito.org

Link to Javadoc: 链接到Javadoc:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM