我的存根总是返回null值mockito

时间:2017-08-27 08:40:00

标签: java junit mockito

在下面的代码中我试图模拟一个EmailService类和stub方法发送带有一些值的message1,但它总是返回null值

zip(*...)

FacebookService

package com;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestFile {

    private FacebookService facebookService;

    @Mock
    private EmailService mockedEmailService;

    @Before
    public  void setUp() {
        EmailService emailService = mock(EmailService.class);
        when(emailService.sendMessage1("1","1")).thenReturn("dfdfgdfg");
         facebookService = new FacebookService(emailService);

    }

    @Test
    public void testSendMessage() {
        String actualResult = facebookService.sendMessage("msg", "recepient");
        System.out.println(actualResult);
    }
}

1 个答案:

答案 0 :(得分:3)

您目前只匹配/存根sendMessage1("1","1"),但通过sendMessage1("A","B")sendMessage1("","")调用,可能您应该这样做:

when(emailService.sendMessage1(anyString(), anyString())).thenReturn("dfdfgdfg");

您需要为此导入https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/ArgumentMatchers.html#anyString()