Mockito没有模拟出成员变量方法的返回值

时间:2018-11-25 07:36:43

标签: java spring-boot junit mockito

我有以下包含成员变量的类,但是Mockito似乎无法模拟成员变量的方法。下面是我的被测系统:

public class MessageConsumer {

    private ConsumerResponse consumerResponse;
    private NotificationConsumer notificationConsumer;

    @Scheduled(cron = "${com.example.value}")
    public void fetch() {
        consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
        System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
    }

    public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
        this.consumerResponse = consumerResponse;
    }

    public ConsumerResponse getConsumerResponse() {
        return consumerResponse;
    }
}

以下是该类的相关JUnit测试:

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

    @Mock
    private ConsumerResponse consumerResponse;

    @InjectMocks
    private MessageConsumer messageConsumer;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    //Failing unit test
    @Test
    public void getResponseCodeShouldReturn200() {
        Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
        messageConsumer.fetch()
    }

}

如您所见,我模拟了ConsumerResponse consumerResponse变量,以在调用"200"方法时返回consumerResponse.getResponseCode()。相反,我得到一个NullPointerException

我敢肯定,我正确地嘲笑了成员变量并适当地对其进行了初始化(initMocks)。我花了几天的时间试图解决这个问题。我要去哪里错了?

1 个答案:

答案 0 :(得分:3)

由于NotificationConsumer也是此类的外部依赖项,因此您还必须模拟该类,否则consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse();将在测试中进入null,因为您没有模拟NotificationConsumer。另外,我建议不要在此单元测试中使用@SpringBootTest,因为此注释将引导整个Spring上下文。以下代码片段应为您提供帮助:

@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {

    @Mock
    private ConsumerResponse consumerResponse;

    @Mock
    private NotificationConsumer notificationConsumer;

    @InjectMocks
    private MessageConsumer messageConsumer;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getResponseCodeShouldReturn200() {
        Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
        Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
        messageConsumer.fetch();
    }

}