我正在测试一个在其下使用 Dao 层的服务类。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AppServiceTest {
@Autowired
@InjectMocks
private AppService appService;
private AppConfig appConfig = new AppConfig(), appConfigOut = new AppConfig();
@MockBean //This statement is under inspection in the problem
private AppDao appDao;
@Before
public void setUp() throws Exception {
String appKey = "jsadf87bdfys78fsd6f0s7f8as6sd";
appConfig.setAppKey(appKey);
appConfigOut.setAppKey(appKey);
appConfigOut.setRequestPerMinute(null);
appConfigOut.setRequestDate(DateTime.now());
MockitoAnnotations.initMocks(this);
}
@Test
public void testFetchAppConfigValidParam() throws Exception {
when(appDao.fetchAppConfig(appConfig)).thenReturn(appConfigOut);
assertThat(appService.fetchAppConfig(appConfig)).isEqualToComparingFieldByField(appConfigOut);
}
在上面的程序中,当我编写@MockBean
时,测试会抛出NullPointerException,但是当我编写@Mock
时,测试会成功执行。我认为被调用的 appDao 是在 appService
中定义并访问数据库的实际 appDao。这是因为测试所需的时间约为 200ms,而其他应用程序的通常测试用例为 60ms-100ms。但我不确定,因为其他情况下 DAO 真正访问数据需要 400ms 到 500ms。
我如何知道模拟实际上正在工作,并且当 appService
从内部调用 appDao
方法时,它实际上是模拟。有没有任何编程方式来验证这一点。
附注如果 @Mock
在这种情况下工作,那么 @MockBean
在 Spring Boot 中很有用。
最佳答案
M.Deinum 在评论中为您指明了正确的方向。
也许您想阅读有关测试中的模拟和 spy Activity 的 Spring 文档 - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-mocking-beans
但要回答你的问题 - 你可以使用 MockingDetails
来判断一个对象是否是模拟对象。
MockingDetails mockingDetails = org.mockito.Mockito.mockingDetails(appDao)
boolean appDaoIsMock = mockingDetails.isMock()
关于java - 如何知道 Spring boot 中是否使用了 Mock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42827811/