Sob*_*van 11 java mocking mockito stubbing
我遇到了mockito的问题.我正在开发一个Web应用程序.在我的测试中,用户管理被嘲笑.在某些情况下,我必须更改getLoggedInUser()方法返回的用户.
问题是,我的getLoggedInUser()方法也可以抛出一个AuthenticationException.
所以当我尝试从没有用户切换到某个用户时,调用
when(userProvider.getLoggedInUser()).thenReturn(user);
Run Code Online (Sandbox Code Playgroud)
抛出异常,就像userProvider.getLoggedInUser()已经存在的那样thenTrow()
有没有办法告诉when方法不关心异常?
提前谢谢 - István
小智 16
在新的Mockito版本中,您可以使用存根连续调用在第一个可以抛出异常并在第二个调用时返回一个值.
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
Run Code Online (Sandbox Code Playgroud)
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#stubbing_consecutive_calls
我对你的问题的第一反应是,听起来你在一次测试中尝试做的太多了。
为了便于测试和简单,每个测试应该只测试一件事。这与单一职责原则相同。我经常发现程序员试图在一个测试中测试多个东西,并因此遇到各种各样的问题。因此,您的每个单元测试方法都应遵循以下流程:
所以在你的情况下,我希望看到至少两个测试。一个getLoggedInUser()返回用户,一个getLoggedInUser()抛出异常。这样你就不会在模拟中尝试模拟不同的行为时遇到问题。
想到的第二个想法是不要存根。考虑使用 expect 代替,因为您可以设置一系列期望。即第一个调用返回一个用户,第二个调用抛出一个异常,第三个调用返回一个不同的用户,等等。
有什么方法可以告诉when方法不关心异常吗?
实际回答这个问题:
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
public class MyTest {
@Test
public void testA() {
// setup
ArrayList<Object> list = mock(ObjectArrayList.class);
when(list.indexOf(any())).thenReturn(6);
when(list.indexOf(any())).thenReturn(12);
// execute
int index = list.indexOf(new Object());
// verify
assertThat(index, is(equalTo(12)));
}
@Test
public void testB() {
// setup
ArrayList<Object> list = mock(ObjectArrayList.class);
when(list.add(any())).thenThrow(new AssertionError("can't get rid of me!"));
when(list.add(any())).thenReturn(true);
// execute
list.add(new Object());
}
@Test
public void testC() {
// setup
ArrayList<Object> list = mock(ObjectArrayList.class);
when(list.add(any())).thenThrow(new AssertionError("can't get rid of me!"));
Mockito.reset(list);
when(list.add(any())).thenReturn(true);
// execute
list.add(new Object());
}
/**
* Exists to work around the fact that mocking an ArrayList<Object>
* requires a cast, which causes "unchecked" warnings, that can only be suppressed...
*/
class ObjectArrayList extends ArrayList<Object> {
}
}
Run Code Online (Sandbox Code Playgroud)
TestB由于断言您无法摆脱而失败。TestC展示了如何使用该reset方法重置模拟并删除其thenThrow上的命令。
请注意,在我拥有的一些更复杂的示例中,重置似乎并不总是起作用。我怀疑这可能是因为他们在使用PowerMockito.mock而不是Mockito.mock?
| 归档时间: |
|
| 查看次数: |
9337 次 |
| 最近记录: |