简体   繁体   English

如何使用Mockito在Service类中测试void方法?

[英]How test a void method into Service class, with Mockito?

I need to make pass all my test and to reach a complete code coverage for all classes of my project. 我需要通过所有测试,并获得项目所有类的完整代码覆盖率。

I created a Repository, Service and Controller class. 我创建了一个Repository,Service和Controller类。

I need to test all single method into these classes. 我需要将所有单个方法测试到这些类中。

I have these classes: 1) ApplicationController with ApplicationControllerTest 2) UserService with UserServiceTest 3) UserRepository with UserRepositoryTest 我有这些类:1)带ApplicationControllerTest的ApplicationController 2)带UserServiceTest的UserService 3)带UserRepositoryTest的UserRepository

This is the controller: 这是控制器:

 @Controller
    @RequestMapping("/")
    @SessionAttributes("user")
    public class ApplicationWebController {

    @Autowired
    private UserService userService;

    @Autowired
    private FundService fundService;

    @PostMapping("/save-user")
    public String saveUser(User user, Model model) {
        final User presentUsername = 
    userService.getUserByUsername(user.getUsername());
        if (presentUsername == null) {
            userService.insertNewUser(user);
            if((user.getUsername()).equals("admin")) {
                userService.updateRoleToAdmin(user.getId());
            }
    }

Here I insert a new User; 我在这里插入一个新用户; if User.username is equal to "admin" then I update the field "role" with userService.updateRoleToAdmin(user.getId()) 如果User.username等于“ admin”,那么我使用userService.updateRoleToAdmin(user.getId())更新字段“ role”

This is the JUnit test for controller: 这是针对控制器的JUnit测试:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ApplicationWebController.class)
public class ApplicationWebControllerTest {

@Autowired
private WebClient webClient;

@MockBean
private UserService userService;

@Test
public void test_whenInsertedUserIsAdmin_DoUpdateOnRole() throws 
Exception {

User userInserted = new User(1L, "admin", "password", 1);       

mvc.perform(post("/save-user")
        .param("id", "1")
        .param("username", "admin")
        .param("password", "password")
        .param("role", "1"));

if (userInserted.getUsername() == "admin") {
    verify(userService).updateRoleToAdmin(1L);
}
}
}

this test correctly pass. 此测试正确通过。

Now I have the Service class and the relative test class 现在我有Service类和相对测试类

This is the Service class 这是服务类

@Service
public class UserService {

private UserRepo userRepo;

public void updateRoleToAdmin(Long id) {
    userRepo.updateRoleToAdmin(id);
}
}

This class also must be tested and this is the JUnit class for the Service 该类也必须经过测试,这是Service的JUnit类

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

@Mock
private UserRepo userRepo;

@InjectMocks
private UserService userService;

@Test
public void test_updateRoleToAdmin() {
//I DON'T KNOW HOW WRITE HERE
        //I NEED TO TEST THE RESPECTIVE METHOD IN SERVICE CLASS
        //THE METHOD IN userRepo IS A VOID METHOD 
}
}

These are my Repository classes (class and JUnit test) 这些是我的存储库类(类和JUnit测试)

public interface UserRepo extends JpaRepository<User, Long> {

@Modifying(flushAutomatically = true, clearAutomatically = true)
@Transactional
@Query("update User u set u.role = 2 where u.id = :userid")
void updateRoleToAdmin(@Param("userid") Long id);

}

The test for the Repo class: 回购类的测试:

@Test
public void test_UpdateRoleToAdmin() {
User user = new User(null, "admin", "password", 1);
User saved = userRepo.save(user);
userRepo.updateRoleToAdmin(saved.getId());
User found = userRepo.findByUsername("admin");
assertThat(found.getRole()).isEqualTo(2);
}

also, this test correctly pass 此外,此测试正确通过

Now I must write a test into UserServiceTest JUnit test class. 现在,我必须将测试写入UserServiceTest JUnit测试类。

I don't know what should I do, because it's a void method and I can't use when(method).thenReturn(..) and the following Assertion 我不知道该怎么办,因为这是一个无效方法,我不能使用when(method).thenReturn(..)和以下断言

I must have a Code Coverage of 100% for all my classes and without test the method "UserService.updateRoleToAdmin(Long id)" I can't reach it. 我必须为所有类提供100%的代码覆盖率,并且未经测试“ UserService.updateRoleToAdmin(Long id)”方法就无法达到。

Please help, because I don't know how to test a void method there. 请帮忙,因为我不知道如何在此处测试void方法。

Thank you. 谢谢。 I need to make pass all my test and to reach a complete code coverage for all classes of my project. 我需要通过所有测试,并获得项目所有类的完整代码覆盖率。

I created a Repository, Service and Controller class. 我创建了一个Repository,Service和Controller类。

I need to test all single method into these classes. 我需要将所有单个方法测试到这些类中。

You should test what is happening inside of the SUT method. 您应该测试SUT方法内部发生的情况。 You already have the repo mocked so just verify behaviour in the test: 您已经模拟了存储库,因此只需在测试中验证行为即可:

@Test
public void shouldUpdateRoleToAdmin() {
    // When
    userService.updateRoleToAdmin(anyLong());

    // Then
    verify(userRepo, times(1)).updateRoleToAdmin(anyLong()); 
}

after you have invoked the method with a certain id . 在调用具有特定id的方法之后。

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

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