【发布时间】:2011-12-28 12:24:27
【问题描述】:
我正在为我的 Spring 应用程序中的服务层编写单元测试。
这是我的服务类
@Service
public class StubRequestService implements RequestService {
@Autowired
private RequestDao requestDao;
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
@Override
public Request getRequest(Long RequestId) {
Request dataRequest = requestDao.find(requestId);
return dataRequest;
}
}
这是我的测试课
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
public class StubRequestServiceTest {
@Mock
public RequestDao requestDao;
StubRequestService stubRequestService; // How can we Autowire this ?
@org.junit.Before
public void init() {
stubRequestService = new StubRequestService(); // to avoid this
stubRequestService.setRequestDao(dataRequestDao);
// Is it necessary to explicitly set all autowired elements ?
// If I comment/remove above setter then I get nullPointerException
}
@Test
public void testGetRequest() {
Request request = new Request();
request.setPatientCnt("3");
when(requestDao.find(anyLong())).thenReturn(request);
assertEquals(stubRequestService.getRequest(1234L).getPatientCnt(),3);
}
}
它工作正常,但我有几个问题
- 我们如何在测试中
Autowire服务类?我在init()方法中使用构造函数来创建服务对象。 - 我们是否必须为服务类设置所有
Autowire元素?例如StubRequestService已自动连接RequestDao,我需要在调用测试方法之前明确设置它,否则它会在requestDao中给出nullPointerExceptionrequestDao是null在StubRequestService.getRequest方法中。 - 在对 Spring 服务层进行单元测试时应遵循哪些良好实践? (如果我做错了什么)。
【问题讨论】:
-
如果你在给出答案后改变了你的问题,那么答案就没有多大意义了。我会回滚你上次的编辑。
-
@JB:抱歉编辑问题。我只是想提供正确和准确的信息。谢谢
标签: spring unit-testing mockito