【发布时间】:2022-01-25 19:07:23
【问题描述】:
我正在尝试使用来自 mockito 的 when 调用来模拟方法的返回值。但是,我对此并不陌生,我可能会误解 mockito 的工作原理,因为当调用另一个方法时,调用在被模拟的方法内部失败。我想不管该方法是如何实现的,我都应该得到我想要的返回值?或者我还需要模拟该方法的内部结构吗?我觉得不应该。
public boolean verifyState(HttpServletRequest request, String s) {
String stateToken = getCookieByName(request, STATE_TOKEN);
String authToken = getCookieByName(request, AUTHN);
boolean isValidState = true;
if (isValidState) {
try {
log.info(getEdUserId(stateToken, authToken));
return true;
} catch (Exception e) {
ExceptionLogger.logDetailedError("CookieSessionUtils.verifyState", e);
return false;
}
} else {
return false;
}
}
public String getEdUserId(String stateToken, String authToken) throws Exception {
String edUserId;
Map<String, Object> jwtClaims;
jwtClaims = StateUtils.checkJWT(stateToken, this.stateSharedSecret); // Failing here not generating a proper jwt token
log.info("State Claims: " + jwtClaims);
edUserId = sifAuthorizationService.getEdUserIdFromAuthJWT(authToken);
return edUserId;
}
我的测试:
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
@WebMvcTest(value = CookieSessionUtils.class, includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {ApiOriginFilter.class, ValidationFilter.class})})
class CookieSessionUtilsTest {
@Autowired
private CookieSessionUtils cookieSessionUtils; // Service class
@Mock
private CookieSessionUtils cookieSessionUtilsMocked; // Both the method under test and the one mocked are under the same class, so trying these two annotations together.
@Mock
private HttpServletRequest request;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testVerifyState1() throws Exception {
//...Some mocks for getCookieName
UUID uuid = UUID.randomUUID();
when(cookieSessionUtils.getEdUserId(anyString(), anyString()).thenReturn(eq(String.valueOf(uuid))); // When this line runs it fails on verifyState method
assertTrue(cookieSessionUtils.verifyState(request, ""));
}
更新
尝试使用 anyString() 而不是 eq()。
谢谢。
【问题讨论】:
-
您的代码有错字:
when(cookieSessionUtils...->when(cookieSessionUtilsMocked...和cookieSessionUtils.verifyState->cookieSessionUtilsMocked.verifyState。顺便说一句,如果您正在测试CookieSessionUtils本身,为什么要嘲笑它?您需要在测试类中模拟服务,而不是类本身 -
不是错字。被测方法和要模拟的方法都在同一个类下,所以我尝试使用正在自动装配的类和模拟版本调用一个。
-
它不是那样工作的。 Lesiak 是对的,你不能将 Mockito 注入到 spring 上下文中
标签: java spring-boot unit-testing mockito spring-test