简体   繁体   中英

Is this code, using (Mockito and JUnit) a good way to test a method getById from my @Service?

I am using mockito to write some unit tests and I'm not sure if this test is satisfactory for method 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);
}

Is this test correct? Any advice or another way to write this test?

The idea of mocking is that the method you want to test of your SUT (System under Test) depends on a collaborator that you can't set up for the test. So you mock this collaborator. Let

  • S be the SUT
  • m() be a method of SUT which you want to test
  • t be a test method that creates an instance of S and calls m() on it
  • C be a collaborator that S depends on
  • n() be aa method on C that ist called inside m() .

Now let's assume that it is difficult to set up C so you want to mock it.

interface C {
  String n();
}
@Mock
private C cMock;

For your test method you instruct cMock to answer in a way that makes m() behave in a way you want to test.

@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();
}

Since you are doing TDD (you are, aren't you?), you can now start to implement 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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM