我正在使用Mockito编写测试。我的课看起来像这样:
@RunWith(MockitoJUnitRunner.class)
public class MailContainsAttachmentJsonFilterTest {
private MailContainsAttachmentJsonFilter mailContainsAttachmentJsonFilter;
private JavaMailSender javaMailSender;
@Before
public void setUp() throws Exception {
mailContainsAttachmentJsonFilter = new MailContainsAttachmentJsonFilter();
javaMailSender = new JavaMailSenderImpl();
}
测试:
@Test
public void filterTest01() throws MessagingException, IOException {
MimeMessage mimeMessage = Mockito.mock(MimeMessage.class);
Folder folder = Mockito.mock(Folder.class);
Mockito.when(folder.isOpen()).thenReturn(true);
Mockito.when(mimeMessage.getFolder()).thenReturn(folder);
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.addAttachment("test.json", new ByteArrayDataSource("{}", "application/json"));
Mockito.when(mimeMessage).thenReturn(messageHelper.getMimeMessage());
mailContainsAttachmentJsonFilter.filter(mimeMessage);
}
运行测试时,只要达到Mockito.when(folderisOpen()).thenReturn(true)
,我就会得到:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not
supported.
2. inside when() you don't call method on mock but on some other
object.
MimeMessage
和Folder
均来自javax.mail
。
据我所知,我尝试模拟的方法都不是final / private / equals()/ hashcode()。
答案 0 :(得分:1)
您错过了这一行的方法调用:
Mockito.when(mimeMessage).thenReturn(messageHelper.getMimeMessage());
因此,您应该将“ mimeMessage”更改为“ mimeMessage.someMethodCall()”