如何模拟在java中使用注入对象进行单元测试的私有方法?

时间:2017-04-08 11:45:23

标签: java unit-testing junit testng powermockito

为了测试我的DedupServiceWrapperImpl课程,我需要模拟私有方法" isDedupEnabled"和"是新的"。这是考试中的课程:

public class DedupServiceWrapperImpl implements DedupServiceWrapper {

    @Inject
    private DedupService dedupService;

    @Inject
    private EventTypeService eventTypeService;

    @Inject
    private MessageLogService messageLogService;

    private static final Logger logger = LoggerFactory.getLogger(DedupServiceWrapperImpl.class);

public Message dedup(Message message) {
   if (isDedupEnabled(eventTypeName)) {
     System.out.println("Dedup is enabled.");
     if (isNew(digest)) {
         System.out.println("it is new");
     } else {
        System.out.println("is not new");
     }
   } else {
       System.out.println("Dedup is not Enabled");
   }
}

private boolean isNew(Digest digest) {
        return !dedupService.checkIfExists(digest.getDigest());
    }

    private boolean isDedupEnabled(String eventTypeName) {
        boolean result = false;
        try {
            logger.info("Fetching eventType:{} to see if dedup is enabled on it.", eventTypeName);
            EventType eventType = eventTypeService.findByName(eventTypeName);
            if (eventType.isDedupEnabled()) {
                result = true;
            }
        } catch (NotFoundException nfe) {
            logger.warn("EventType '{}' not found!", eventTypeName);
        }
        return result;
    }
}

这是我的单元测试类:

import com.sun.org.apache.bcel.internal.classfile.Method;
import com.tosan.chapar.core.exception.NotFoundException;
import com.tosan.chapar.core.service.DedupService;
import com.tosan.chapar.core.service.MessageLogService;
import com.tosan.chapar.ivr.service.DedupServiceWrapper;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.messaging.MessageHeaders;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
//import org.junit.Test;
import org.springframework.messaging.Message;

import static org.junit.runner.Request.method;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(DedupServiceWrapperImpl.class)
public class DedupServiceWrapperImpl_DedupUTest {

    private static final String payload = "Hello UTest.";
    private Message inputMessage;
    private MessageHeaders messageHeaders;
    //@Mock
    //private DedupService dedupService;
    //@InjectMocks
    private DedupServiceWrapper dedupServiceWrapper;

    @Test
    public void testName() throws Exception {

    }

    @SuppressWarnings("unchecked")
    @BeforeMethod
    public void setupMocks() throws NotFoundException {
        MessageLogService messageLogService = mock(MessageLogService.class);
        /*digest = mock(Digest.class);
        eventType = mock(EventType.class);
        eventType.setName("modern_chaparbo_free");
        eventType.setDedupEnabled(true);

        eventTypeService = mock(EventTypeServiceImpl.class);
        when(eventTypeService.findByName("modern_chaparbo_free")).thenReturn(eventType);*/

        messageHeaders = mock(MessageHeaders.class);
        when(messageHeaders.get("eventTypeName")).thenReturn("modern_chaparbo_free");
        when(messageHeaders.get("recipient")).thenReturn("+982112345678");
        when(messageHeaders.size()).thenReturn(2);

        inputMessage = mock(Message.class);
        when(inputMessage.getHeaders()).thenReturn(messageHeaders);
        when(inputMessage.getPayload()).thenReturn(payload);
    }

    /**
     * dedupEnabled is false
     */
    @Test//(expected = RuntimeException.class)
    public void dedup_Disablededup_dedupeIsNotDone()  throws Exception{
        //doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class))
        DedupServiceWrapperImpl spy = PowerMockito.spy(new DedupServiceWrapperImpl());
        //DedupServiceWrapper spy = mock(DedupServiceWrapperImpl.class);
        PowerMockito.doReturn(false).when(spy, "isDedupEnabled", anyString(),);
        //PowerMockito.verifyPrivate(spy, times(0)).invoke("isDedupEnabled", anyString());
        //PowerMockito.when(spy, method(DedupServiceWrapperImpl.class, "isDedupEnabled", String.class)).withArguments(anyString()).thenReturn(false);
        //PowerMockito.verifyPrivate(spy, times(2)).invoke("isDedupEnabled", anyString());
        //PowerMockito.doReturn(false).when(spy, method(DedupServiceWrapperImpl.class, "isDedupEnabled", String.class)).withArguments(anyString());
        /*DedupServiceWrapper truck = new DedupServiceWrapperImpl();
        DedupServiceWrapper truckSpy = PowerMockito.spy(truck);
        PowerMockito.doReturn(false).when(truckSpy,
                "isDedupEnabled");*/
        Message message = spy.dedup(inputMessage);
        org.junit.Assert.assertEquals(inputMessage, message);
        assertNotNull(message);
        assertEquals(message, inputMessage);
    }


}

我已经在我的测试课程中尝试了所有样本,但它们不起作用,我让它们发表评论......

我无法模拟私有方法 - 我怎么能这样做?为什么不起作用?

它抛出了这个:

Method threw 'org.mockito.exceptions.misusing.WrongTypeOfReturnValue' exception. Cannot evaluate com.tosan.chapar.ivr.service.impl.DedupServiceWrapperImpl$$EnhancerByMockitoWithCGLIB$$9a511df1.toString()

2 个答案:

答案 0 :(得分:1)

可以使用PowerMock模拟私有方法,或者您可以考虑使用Mockito间谍进行部分模拟。

但大多数情况下,对这些技巧的需求是一种不足的设计。换句话说:改为尝试修复难以测试的生产代码的症状......而是花时间让代码易于测试。

答案 1 :(得分:0)

您将TestNG(org.testng.annotations.*)和JUnit(org.junit.runner.*)混合在同一个不允许的类中。

如果您想使用PowerMock和TestNG,则需要扩展PowerMockTestCase。查看文档:{​​{3}}