例如,要在控制器中对insertCategory()方法进行存根以始终返回"failure",请执行以下操作:when(categeoryCntrlr.insertCategory(any())).thenReturn("failure");这里有更多有关验证交互和存根方法调用的示例: http://mockito.org 链接到Javadoc: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html 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 ? 解决方案 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.orgLink to Javadoc:http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html 这篇关于使用Mockito/JUnit-Database操作进行Java应用程序的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 05:24