print code location in warning message

This commit is contained in:
金戟 2020-11-16 14:16:58 +08:00
parent 80499f0da2
commit 648e4aa9cc
2 changed files with 13 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package com.alibaba.testable.core.tool;
import com.alibaba.testable.core.error.VerifyFailedError; import com.alibaba.testable.core.error.VerifyFailedError;
import com.alibaba.testable.core.model.Verification; import com.alibaba.testable.core.model.Verification;
import com.alibaba.testable.core.util.TestableUtil;
import java.security.InvalidParameterException; import java.security.InvalidParameterException;
import java.util.List; import java.util.List;
@ -137,7 +138,7 @@ public class InvokeVerifier {
*/ */
public InvokeVerifier withTimes(int expectedCount) { public InvokeVerifier withTimes(int expectedCount) {
if (expectedCount != records.size()) { if (expectedCount != records.size()) {
throw new VerifyFailedError("times: " + records.size(), "times: " + expectedCount); throw new VerifyFailedError("times: " + expectedCount, "times: " + records.size());
} }
lastVerification = null; lastVerification = null;
return this; return this;
@ -150,8 +151,8 @@ public class InvokeVerifier {
public InvokeVerifier times(int count) { public InvokeVerifier times(int count) {
if (lastVerification == null) { if (lastVerification == null) {
// when used independently, equals to `withTimes()` // when used independently, equals to `withTimes()`
System.out.println("Warning: using \"times()\" check without \"with()\" or \"withInOrder()\" method " + System.out.println("Warning: [" + TestableUtil.getPreviousStackLocation() + "] using \"times()\" method "
"is not recommended, please use \"withTimes()\" instead."); + "without \"with()\" or \"withInOrder()\" is not recommended, please use \"withTimes()\" instead.");
return withTimes(count); return withTimes(count);
} }
if (count < 2) { if (count < 2) {

View File

@ -50,6 +50,15 @@ public class TestableUtil {
return ""; return "";
} }
/**
* Get file name and line number of where current method was called
*/
public static String getPreviousStackLocation() {
// 0 - Thread.getStackTrace(), 1 - this method, 2 - code call this method, 3 - code call the caller method
StackTraceElement stack = getMainThread().getStackTrace()[3];
return stack.getFileName() + ":" + stack.getLineNumber();
}
private static String findLastMethodFromSourceClass(String sourceClassName, StackTraceElement[] stack) { private static String findLastMethodFromSourceClass(String sourceClassName, StackTraceElement[] stack) {
for (StackTraceElement element : stack) { for (StackTraceElement element : stack) {
if (element.getClassName().equals(sourceClassName)) { if (element.getClassName().equals(sourceClassName)) {