如何编写基于Mockito的JUnit方法来测试此方法adduser()?我试着写一个,但它失败了,错误信息说异常没有被处理。错误显示为:when(service.addUser("nginx")).thenReturn("apache");假设业务类中的addUser()方法永远不会捕获任何异常并且不会重新抛出。classBusiness{publicUseraddUser()throwsServiceException{Useruser=service.addUser("nginx");returnuser;}}测试用例方法:在测试类中,我使用@Mock属性模拟服务层类并注入(in
我正在尝试编写一个单元测试,为此我正在为Mockito模拟编写一个when语句,但我似乎无法让eclipse认识到我的返回值是有效的。这就是我正在做的事情:ClassuserClass=User.class;when(methodParameter.getParameterType()).thenReturn(userClass);.getParameterType()的返回类型是Class,所以我不明白为什么eclipse说,ThemethodthenReturn(Class)inthetypeOngoingStubbing>isnotapplicablefortheargument
已结束。此问题不符合StackOverflowguidelines.它目前不接受答案。要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于StackOverflow来说是无关紧要的,因为它们往往会吸引固执己见的答案和垃圾邮件。相反,describetheproblem以及到目前为止为解决这个问题所做的工作。关闭8年前。Improvethisquestion我需要使用mockito为现有代码创建单元测试框架。我找不到开始学习Mockito的好地方。你能给我指出一个很好的mockito学习资源吗?(在线资源或其他) 最佳答案 在Hel
我有一个有2个方法的类。我想模拟类,然后模拟第一个方法,而不是第二个。例如classC{voidm1(){...}booleanm2(){...returnflag;}}单元测试代码:CcMock=Mockito.mock(C.class);Mockito.doNothing().when(cMock).m1();Mockito.when(cMock.m2()).thenCallRealMethod();奇怪的是m2没有被调用。我有什么想念的吗? 最佳答案 这也是Mockito.spy可以使用的地方。它允许您对真实对象进行部分模拟。
假设我在某个服务类中有以下方法:publicSomeEntitymakeSthWithEntity(someArgs){SomeEntityentity=newSomeEntity();/***heregoessomelogicconcerningtheentity*/returnrepository.merge(entity);}我想测试此方法的行为,因此想以以下方式模拟repository.merge:when(repository.merge(any(SomeEntity.class))).thenReturn(objectPassedAsArgument);然后模拟存储库返回m
我有这样声明的方法privateLongdoThings(MyEnumenum,LongotherParam);还有这个枚举publicenumMyEnum{VAL_A,VAL_B,VAL_C}问题:如何模拟doThings()调用?我无法匹配任何MyEnum。以下不起作用:Mockito.when(object.doThings(Matchers.any(),Matchers.anyLong())).thenReturn(123L); 最佳答案 Matchers.any(Class)可以解决问题:Mockito.when(obje
我对它们之间的区别以及在哪种情况下选择哪个感到困惑。有些区别可能很明显,例如any和eq,但我将它们都包括在内只是为了确定。我想知道它们的区别,因为我遇到了这个问题:我在Controller类中有这个POST方法publicResponsedoSomething(@ResponseBodyRequestrequest){returnsomeService.doSomething(request);}并且想对该Controller执行单元测试。我有两个版本。第一个是简单的,像这样@TestpublicvoidtestDoSomething(){//initializeObjectMapp
我有一节课。ClassFirst{privateSecondsecond;publicFirst(intnum,Stringstr){second=newSecond(str);this.num=num;}...//someothermethods}我想为First类的公共(public)方法编写单元测试。我想避免执行Second类的构造函数。我这样做了:Secondsecond=Mockito.mock(Second.class);Mockito.when(newSecond(any(String.class))).thenReturn(null);Firstfirst=newFir
我有一个使用当前时间进行一些计算的函数。我想用mockito来模拟它。我想测试的类的一个例子:publicclassClassToTest{publiclonggetDoubleTime(){returnnewDate().getTime()*2;}}我想要类似的东西:@TestpublicvoidtestDoubleTime(){mockDateSomeHow(Date.class).when(getTime()).return(30);assertEquals(60,newClassToTest().getDoubleTime());}可以模拟吗?我不想更改“已测试”代码以便进行测
我正在使用mockito验证一个方法已被调用。方法:publicvoidcreateButtons(finalListbuttonsConfiguration){...}由于传递哪个列表并不重要,因此我验证该方法的调用如下:verify(mock).createButtons(Matchers.anyListOf(Button.class));但是,List的大小很重要。因此,哪个List并不重要,但列表必须有X个元素。这可能吗? 最佳答案 一种方法是使用CaptorArgumentCaptorcaptor=ArgumentCapt