简体   繁体   English

如何在 Java 中模拟可选类?

[英]How do I mock an optional class in java?

I was mocking my crud app and I was trying to mock the update API.我在嘲笑我的 crud 应用程序,我试图嘲笑更新 API。 As findById() method belongs to Optional class, I can't find a way to mock it.由于 findById() 方法属于 Optional 类,我找不到模拟它的方法。 Here is the code snippet.这是代码片段。

@Mock
@Autowired
private UserRepository repo;

@Test
public void testUpdateUser() {
    Integer userId = 3;

    Optional<User> optionalUser = repo.findById(userId);

    User user = optionalUser.get();
    user.setFirstName("Paul");
    repo.save(user);

    User updatedUser = repo.findById(userId).get();
    Assertions.assertThat(updatedUser.getFirstName()).isEqualTo("Paul");
}
@Mock
@Autowired
private UserRepository repo;

This part of your code can lead to confusion.这部分代码可能会导致混淆。 The principle behind mocking is to create a mock objects that is used by the class you want to test.背后的原理mocking是创建一个mock所使用的要测试的类的对象。

Looks like you want to test your repository.看起来您想测试您的存储库。 To do that you can use test slice with @DataJpaTest .为此,您可以将测试切片@DataJpaTest一起@DataJpaTest

Then in your case, you don't need to mock the optional .那么在你的情况下,你不需要模拟optional .

In case you want to test a Service class or another class that use your UserRepository , you will define a mock and your class will looks like this :如果您想测试使用UserRepositoryService类或其他类,您将定义一个mock ,您的类将如下所示:

@Mock
private UserRepository repo;

@InjectMocks
private UserService service;

@Test
public void testUpdateUser() {

    when(repo.findById(anyInt()).get()).thenReturn(aNewInstanceOfUser());

    ...

}

For more reading .更多阅读

Optional class is a final class, so you cannot mock this class with Mockito.可选类是最终类,所以你不能用 Mockito 模拟这个类。 You should use PowerMockito.您应该使用 PowerMockito。 I add below a sample code.我在下面添加了一个示例代码。 Please try this.请试试这个。

@RunWith(PowerMockRunner.class)
@PrepareForTest(Optional.class)
public class PowerMockitoExample {


    @Mock
    Optional<User> optionalMock;

    @Mock Repository repo;

    @Test
    public void testUpdateUser() {
    
      //edit your mock user
      User yourUserData = null;
      
      Mockito.when(repo.findById(Matchers.anyInt())).thenReturn(optionalMock);
      PowerMockito.when(optionalMock.get()).thenReturn(yourUserData);
    
      Integer userId = 3;

      Optional<User> optionalUser = repo.findById(userId);

      User user = optionalUser.get();
      user.setFirstName("Paul");
      repo.save(user);

      User updatedUser = repo.findById(userId).get();
      Assertions.assertThat(updatedUser.getFirstName()).isEqualTo("Paul");
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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