我正在使用mockito编写一些单元测试,我不确定这个测试是否适合方法getById。
@Mock
private CustomerService customerService;
@Test
public void Customer_Get_By_ID() {
Customer customer = Customer.builder()
.firstName("Name")
.lastName("Last Name")
.email("name.last@mail.com")
.build();
Long customerId = customerService.create(customer);
assertNotNull(customerId);
when(customerService.get(customerId)).thenReturn(customer);
Customer saved = customerService.get(customerId);
assertEquals(saved.getFirstName(), customer.getFirstName());
assertEquals(saved.getLastName(), customer.getLastName());
verify(customerService, times(1)).get(customerId);
}
这个测试正确吗? 有什么建议或其他方法来编写这个测试吗?
最佳答案
模拟的想法是,您想要测试 SUT(被测系统)的方法取决于您无法为测试设置的协作者。所以你 mock 这个合作者。让
S
是 SUTm()
是您要测试的 SUT 方法t
是一个测试方法,用于创建S
实例并对其调用m()
C
是S
所依赖的协作者n()
是C
上的一个方法,在m()
内部调用。
现在让我们假设设置 C
很困难,因此您想模拟它。
interface C {
String n();
}
@Mock
private C cMock;
对于您的测试方法,您指示 cMock
以一种使 m()
以您想要测试的方式运行的方式进行回答。
@Test
public void t() {
when(cMock.n()).thenReturn("you've called n()");
// S depends on a C.
S sut = new S(cMock);
// Execute the method of the SUT you want to test.
String result = sut.m();
// Verify the result.
assertThat(result).isEqualTo("C said: you've called n()");
// Optional: Verify that n() was called as expected.
verify(cMock).n();
}
既然您正在进行 TDD(您是,不是吗?),您现在可以开始实现 m()
。
public class S {
C c;
public S(C c) {
this.c = c;
}
public String m() {
// TODO implement me by calling c.n()
return null;
}
}
关于java - 这段代码使用(Mockito 和 JUnit)是测试我的 @Service 中的 getById 方法的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57728850/