PowerMock при новой проблеме в конструкторе компонентов Spring - PullRequest
0 голосов
/ 29 марта 2020

У меня есть Spring Service, как показано ниже:

@Service
public class SendWithUsService
{
    private SendWithUs mailAPI;

    public SendWithUsService()
    {
        this.mailAPI = new SendWithUs();
    }

    public void sendEmailEvent(Dto data)
    {
        try
        {
            SendWithUsSendRequest request = new SendWithUsSendRequest()...;
            mailAPI.send(request);
        }
        catch (Exception e)
        {
           ...
        }
    }
}

И мой тестовый код выглядит следующим образом:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.net.ssl.*"})
@PrepareForTest(SendWithUsService.class)
public class SendWithUsServiceTest
{
    @InjectMocks
    private SendWithUsService sendWithUsService;

    @Mock
    private SendWithUs mailAPI;

    @Test
    public void sendEmailEvent_successfully() throws Exception
    {
        whenNew(SendWithUs.class).withAnyArguments().thenReturn(mailAPI);
        Dto emailData = ...;
        sendWithUsService.sendEmailEvent(emailData);
        ...
    }
}

Здесь, PowerMock метод whenNew не работает. Но когда я вызываю его вне конструктора, как внутри метода sendEmailEvent, он срабатывает.

Есть ли способ справиться с этим?

Работы:

public void sendEmailEvent(Dto data)
{
   this.mailAPI = new SendWithUs();
    ...
}

Не работает:

 public SendWithUsService()
    {
        this.mailAPI = new SendWithUs();
    }

1 Ответ

0 голосов
/ 29 марта 2020

Я решил это, как показано ниже:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.net.ssl.*"})
@PrepareForTest(SendWithUsService.class)
public class SendWithUsServiceTest
{
    @InjectMocks
    private SendWithUsService sendWithUsService;

    @Mock
    private SendWithUs mailAPI;

    @Before
    public void setUp() throws Exception {   
      whenNew(SendWithUs.class).withAnyArguments().thenReturn(mailAPI);
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void sendEmailEvent_successfully() throws Exception
    {
        Dto emailData = ...;
        sendWithUsService.sendEmailEvent(emailData);
        ...
    }
}
...