Java 模拟方法返回Null

Java 模拟方法返回Null,java,junit,integration-testing,mockito,Java,Junit,Integration Testing,Mockito,我试图模拟一些方法调用,但不幸的是,我一直得到null返回。你能帮我指出哪里出了问题吗?我使用的是when().thenReturn(),我觉得我正确地模拟了return变量。非常感谢。我刚接触JUnit和Mockito,所以如果我遗漏了任何明显的东西,我深表歉意 ServiceTest.java @IntegrationTest public class ServiceTest extends TransactionalTest { private HistoryService ord

我试图模拟一些方法调用,但不幸的是,我一直得到null返回。你能帮我指出哪里出了问题吗?我使用的是when().thenReturn(),我觉得我正确地模拟了return变量。非常感谢。我刚接触JUnit和Mockito,所以如果我遗漏了任何明显的东西,我深表歉意

ServiceTest.java

@IntegrationTest
public class ServiceTest extends TransactionalTest {
    private HistoryService orderHistoryService;
    private CMSSiteModel website;

@Mock
protected DefaultWebService orderDetailsServiceWrapper;
@Mock
protected WebsiteService websiteService;    

@Before
public void setUp()
{
    MockitoAnnotations.initMocks(this);
    website = mock(CMSSiteModel.class);
}

@Test
public void testFindOrderDetailsByConfirmationNumber() {

    when(websiteService.getCurrentSite()).thenReturn(website);

    final ResponseType response = orderHistoryService.findOrderDetailsByConfirmationNumber(OrderTestUtils.CONFIRMATION_NUMBER, OrderTestUtils.LOCATION_NUMBER);

    Assert.assertEquals("Incorrect Approver Name", OrderTestUtils.APPROVER_NAME, response.getApprovedByName());
}
和Service.java

public class HistoryService implements OrderHistoryService {

    @Autowired
    private WebsiteService websiteService;

    @Override
    public OrderDetailsServiceResponseType findOrderDetailsByConfirmationNumber(String confirmationNumber, String locationNumber) {

        CMSSiteModel test = websiteService.getCurrentSite();  //returning null
        odsrHeader.setSource(test.getOrderSource());

    }

}

以下是我的答案:[尝试在一个类中编写单元测试用例]


确保
websiteService
在服务类中是
@Mock

我认为您假设Mockito会自动将
websiteService
注入
OrderHistoryService
。在Mockito执行此操作之前,您需要使用
@InjectMocks
OrderHistoryService
进行注释
injectmock
将创建该类的普通实例,然后尝试用作为给定测试一部分创建的任何模拟类或间谍类填充其字段

例如


HistoryService
中的
websiteService
不是
null
令人担忧。似乎有其他的注入正在某处发生,你最终得到了两个独立的模拟网站服务。一个在测试类中,另一个在
HistoryService
中。您似乎遗漏了相当多的测试类,因此很难确定实际发生了什么。

您在
服务中的
网站服务
设置在哪里?基本上,
orderHistoryService
是在哪里构造的,以及如何构造的?很可能您忘记了在测试的类中注入mock,正如@SotiriosDelimanolis所说的。查看一个快速而好的方法,它返回
null
,或者您是否得到
NullPointerException
public class ServiceTest extends TransactionalTest {
    @InjectMocks
    HistoryService orderHistoryService;

    @Mock
    WebsiteService websiteService;

    ...

}