Search code examples
spring-bootjunitpowermockpowermockitospring-boot-test

PowerMock whenNew Problem On Spring Component Constructor


I have a Spring Service like below:

@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)
        {
           ...
        }
    }
}

And my test code look like below:

@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);
        ...
    }
}

In here, PowerMock whenNew method doesn't work. But when I call it outside of constructor like inside the sendEmailEvent method, it is triggered.

Is there a way to handle it?

Works:

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

Not works:

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

Solution

  • I've solved it like below:

    @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);
            ...
        }
    }