Ank*_*kar 3 java junit mockito spring-boot
Class A
{
public B makeB(int q)
{
return new B(q);
}
public boolean evaluate(int q)
{
B b = makeB(q);
boolean result = b.get();
return result;
}
}
Class B
{
int e;
public B(int w)
{
e=w;
}
public boolean get()
{
//return boolean based on object B
}
}
Class ATest
{
A a = spy(A.class);
B b1 = mock(B.class);
B b2 = mock(B.class);
doReturn(b1).when(a).makeB(5);
doReturn(b2).when(a).makeB(10);
when(b1.get()).thenReturn(true);
when(b2.get()).thenReturn(false);
a.evaluate();
}
Run Code Online (Sandbox Code Playgroud)
=======================
在这里,我想在对象B包含值5时从方法评估返回true,而在对象B包含值10时返回false。
B类来自外部库。
单元测试和模拟的新手。
The other answers are technically correct, but the first thing to understand: you should strive to not use a mocking framework like this.
Keep in mind: the purpose of a mocking framework is only to make testing possible/easier. Your mocking specs should be as simple as possible. Meaning: instead of thinking about having a mock giving different results on different parameters - the better solution is to have distinct tests and mocking specs, like:
@Test
public void testFooWithA() {
when(someMock.foo(eq(whateverA)).thenReturn(bar);
...
@Test
public void testFooWithB() {
when(someMock.foo(eq(whateverB)).thenReturn(somethingElse);
...
Run Code Online (Sandbox Code Playgroud)
There are situations where you have write more sophisticated code to make your mocks "more smart". But most of the time when I had to do that - I stepped backed, and simplified my design under test. In other words: when your tests turn "too complicated" - most often the reason is a too complicated class/method under test.
| 归档时间: |
|
| 查看次数: |
6117 次 |
| 最近记录: |