java - 这段代码使用(Mockito 和 JUnit)是测试我的 @Service 中的 getById 方法的好方法吗?

标签 java spring junit mockito

我正在使用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 是 SUT
  • m() 是您要测试的 SUT 方法
  • t 是一个测试方法,用于创建 S 实例并对其调用 m()
  • CS 所依赖的协作者
  • 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/

相关文章:

java - 全局序列比对中的回溯

java - spring不从maven依赖中读取服务存储库

Spring Boot 应用程序找不到用于 spock-spring 测试的占位符 'spring.embedded.kafka.brokers'

java - 如何创建假数据和数据对象以进行单元测试?

java - 在 Android 应用程序中为 Toast 编写 JUnit 测试

JavaFX - 元素未显示

java - EventSource 中的错误处理

java - 如何创建本地存储库以使用 Eclipse?

java - @RequestParam 与 @PathVariable

java - 如何在 JUnit 中构建自动回复 JMS 监听器(在 OpenEJB 中)