我正在编写单元测试的方法,以找到银行附近我的位置。我嘲弄了这个类并尝试调用这些方法。但是,控件不会转到方法来执行它。下面是单元测试用例。
@Test
public void testFindBanksByGeo() {
String spatialLocation = "45.36134,14.84400";
String Address = "Test Address";
String spatialLocation2 = "18.04706,38.78501";
// 'SearchClass' is class where 'target' method resides
SearchClass searchClass = Mockito.mock(SearchClass.class);
BankEntity bank = Mockito.mock(BankEntity.class);
// 'findAddressFromGeoLocation' and 'getGeo_location' to be mocked. They are called within 'target' method
when(searchClass.findAddressFromGeoLocation(anyString())).thenReturn(Address);
when(bank.getGeo_location()).thenReturn(spatialLocation2);
// 'writeResultInJson' is void method. so needed to 'spy' 'SearchClass'
SearchClass spy = Mockito.spy(SearchClass.class);
Mockito.doNothing().when(spy).writeResultInJson(anyObject(), anyString());
//This is test target method called. **Issue is control is not going into this method**
SearchedBanksEntity searchBanksEntity = searchClass.findNearbyBanksByGeoLocation(spatialLocation, 500);
assertNull(searchBankEntity);
}
我所尝试的也是调用它的真实方法,
Mockito.when(searchClass.findNearbyBanksByGeoLocation(anyString(), anyDouble())).thenCallRealMethod();
这调用真实的方法,但我上面嘲笑的方法执行起来就像真实的方法一样。意思是“被嘲弄的方法”没有返回我要求它们返回的内容。
那么,我在这里做错了什么?方法为什么不执行?
好吧,假设我们有这样的代码:
class Foo {
// has a setter
SomeThing someThing;
int bar(int a) {
return someThing.compute(a + 3);
}
}
我们想要测试foo#bar()
,但是有一个对something
的依赖关系,然后我们可以使用一个模拟:
@RunWith(MockitoJunitRunner.class)
class FooTest {
@Mock // Same as "someThing = Mockito.mock(SomeThing.class)"
private SomeThing someThing,
private final Foo foo;
@Before
public void setup() throws Exception {
foo = new Foo(); // our instance of Foo we will be testing
foo.setSomeThing(someThing); // we "inject" our mocked SomeThing
}
@Test
public void testFoo() throws Exception {
when(someThing.compute(anyInt()).thenReturn(2); // we define some behavior
assertEquals(2, foo.bar(5)); // test assertion
verify(someThing).compute(7); // verify behavior.
}
}
使用模拟,我们可以避免使用真正的something
。
一些阅读:
该方法没有被调用,因为您是在模拟上调用它。您应该在实际对象上调用该方法。
或者您可以在调用方法之前使用类似的内容。
Mockito.when(searchClass.findNearbyBanksByGeoLocation(Mockito.eq(spatialLocation), Mockito.eq(500))).thenCallRealMethod();
但我认为这不是您应该编写测试的方式。首先不应该嘲笑SearchClass。相反,在SearchClass中会有一个依赖项,它为您提供地址和地理位置。你应该嘲笑这种特殊的依赖关系。
在我的代码中,我有时在同一个类中调用public或private方法。这些方法并不是一个很好的候选方法,不适合被拉入自己的类中。我调用的每个方法都在它们自己的单元测试中进行测试。 那么,如果我的类a中有一个方法也在类a中调用这些方法中的每一个,有没有办法模拟这些调用?我当然可以剪切和粘贴我的期望/模拟行为,但这不仅是一件乏味的事情,它混淆了测试的要点,违反了模块化,并且由于无法控制返回的内容,使测
在我的代码中,我有时在同一个类中调用公共或私有方法。这些方法不适合被拉到自己的类中。我调用的这些方法中的每一个都是在它们自己的单元测试中进行测试的。 那么,如果我的类a中有一个方法,它也调用类a中的每个方法,那么有什么方法可以模拟这些调用吗?我当然可以剪切和粘贴我的期望/模拟行为,但这不仅是乏味的,它混淆了测试的重点,违反了模块化,并且由于无法控制返回的内容而使测试更加困难。 如果不是,这种事情通
redis-cli -p 6379 DEBUG sleep 30
redis-cli debug oom redis直接退出。
redis-cli debug segfault
我正在使用Spring boot和Mockito进行测试。我已经能够为服务层编写测试用例,它们工作得很好。但是,针对DAO层的测试用例却没有。在执行测试用例时,被mocked和autowired的对象提供指针。以下是详细情况: 我的类: java: