当调用logger.error
时,有许多不同的东西可以作为第三个参数传递。
如何验证e
是否包含特定的子字符串?
这是我的生产代码..
public class MyClass {
private ILogger logger = Slf4jLogbackLogger
.generateLogger(MyClass.class.getClassLoader().getResource("log_messages.properties"));
public void doSomething() {
logger.info(Optional.empty(), "MyClass.doSomething");
try {
.. do things // throw new RuntimeException("something");
} catch (Exception e) {
logger.error(Optional.empty(), "HANDLE_EXCEPTION", e);
}
}
}
我的测试代码..
@RunWith(MockitoJUnitRunner.class)
public class TestMyClass {
@Mock
private ILogger logger;
@InjectMocks
@Spy
private MyClass myClass = new MyClass();
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testMyClass() throws Exception {
try {
myClass.doSomething();
} catch (Exception e) {
fail("Should not have thrown any exceptions");
}
Mockito.verify(logger, Mockito.times(1)).error(Optional.empty(), "HANDLE_EXCEPTION", "Contains something specific");
}
}
这是我收到的错误..
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 1 recorded:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
尝试过如下操作,但出现相同的错误:
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
Mockito.verify(logger, Mockito.times(1)).error(Optional.empty(), "HANDLE_EXCEPTION", argument.capture());
error
在验证该方法被调用期间的所有参数都需要logger
在您的情况下matchers
。下面是一个使用 matchers
和模拟某些服务类的示例:
@ExtendWith(MockitoExtension.class)
public class SomeTestClass {
private static class MyService {
public void error(Optional<String> op, String msg1, String msg2) {
}
}
@Test
void testMethod() {
MyService myService = Mockito.mock(MyService.class);
myService.error(Optional.empty(), "This is error", "Some error appeared");
Mockito.verify(myService, Mockito.times(1)).error(Mockito.any(), Mockito.eq("This is error"), Mockito.contains("error"));
}
}
这里Mockito.any()
、Mockito.eq()
、Mockito.contains()
是返回匹配器的方法。
若要断言该方法是使用包含给定子字符串的String
调用的Mockito.contains()
请使用匹配器。在这里,您可以找到有关使用匹配器的更多信息。