service类单元测试可以有两种方式
1、使用@Autowired启用上下文的Bean走业务逻辑,适用于debug调试
2、使用@InjectMocks不启用上下文依懒的Bean采用打桩的形式
打桩注意:service通常业务逻辑复杂,Bean的依懒层次可能很深,初用者常犯的问题是想一个测试方法全部测到,虽然有些可以给字段属性赋值的方法来深层次打桩,但难免会有各种各样的困难,初用者在依懒层次很深时可以把不好打桩依懒单独写单元测试
继承的基类MockBaseTest请参考本人文章[junit mockito Base基类]
java
@RunWith(PowerMockRunner.class)
@PrepareForTest({Date.class})
public class AccountServiceTest extends MockBaseTest {
@InjectMocks
private AccountService accountService;
HttpServletRequest request = new MockHttpServletRequest();
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAccount_check() throws Exception {
((MockHttpServletRequest) request).setParameter("version","0.1.0");
Date currDate = DateUtils.parse("2024-01-24 08:00:00",DateUtils.DATE_FORMATE_PATTERN);
PowerMockito.whenNew(Date.class).withAnyArguments().thenReturn(currDate);
AccountVO vo = accountService.queryAccount(1L, VersionUtils.getCurrVersion(request));
Assert.assertEquals("0.1.0", vo.getVersion());
}
}