Java Mockito:如何通过模拟测试我的服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2288386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito: How to test my Service with mocking?
提问by Michael Bavin
I'm new to mock testing.
我是模拟测试的新手。
I want to test my Service method CorrectionService.correctPerson(Long personId)
.
The implementation is not yet written but this it what it will do:
我想测试我的 Service 方法CorrectionService.correctPerson(Long personId)
。实现还没有写,但是它会做什么:
CorrectionService
will call a method of AddressDAO
that will remove some of the Adress
that a Person
has. One Person
has Many Address
es
CorrectionService
将调用的方法AddressDAO
,将删除一些的Adress
一个Person
了。一个Person
有很多Address
es
I'm not sure what the basic structure must be of my CorrectionServiceTest.testCorrectPerson
.
我不确定我的CorrectionServiceTest.testCorrectPerson
.
Also please do/not confirm that in this test i do not need to test if the adresses are actually deleted (should be done in a AddressDaoTest
), Only that the DAO method was being called.
另外请不要/不要确认在这个测试中我不需要测试地址是否真的被删除(应该在 a 中完成AddressDaoTest
),只需要调用 DAO 方法。
Thank you
谢谢
采纳答案by Daniel
A simplified version of the CorrectionService class (visibility modifiers removed for simplicity).
CorrectionService 类的简化版本(为简单起见,删除了可见性修饰符)。
class CorrectionService {
AddressDao addressDao;
CorrectionService(AddressDao addressDao) {
this.addressDao;
}
void correctPerson(Long personId) {
//Do some stuff with the addressDao here...
}
}
In your test:
在您的测试中:
import static org.mockito.Mockito.*;
public class CorrectionServiceTest {
@Before
public void setUp() {
addressDao = mock(AddressDao.class);
correctionService = new CorrectionService(addressDao);
}
@Test
public void shouldCallDeleteAddress() {
correctionService.correct(VALID_ID);
verify(addressDao).deleteAddress(VALID_ID);
}
}
回答by MariuszS
Cleaner version:
清洁版:
@RunWith(MockitoJUnitRunner.class)
public class CorrectionServiceTest {
private static final Long VALID_ID = 123L;
@Mock
AddressDao addressDao;
@InjectMocks
private CorrectionService correctionService;
@Test
public void shouldCallDeleteAddress() {
//when
correctionService.correct(VALID_ID);
//then
verify(addressDao).deleteAddress(VALID_ID);
}
}