我的控制器在运行时中运行,但是由于类中没有的依赖项,mockkmvc测试失败

时间:2018-12-22 16:38:14

标签: java spring-mvc spring-boot testing mockito

运行测试时,我发现无法发现UserService的依赖项错误。这很奇怪,因为在ConstantsController.java中没有使用UserService的地方。另外,UserService可以正确标记@Service标注。

我尝试在控制器测试类中使用@MockBean批注。它给了我无法识别的错误。我什至尝试在配置中自动装配Bean,因为日志说在配置中定义了UserService类型的Bean。还是没有运气。

UserService

package com.GMorgan.RateMyFriendv5.Service;

import com.GMorgan.RateMyFriendv5.Entitiy.Role;
import com.GMorgan.RateMyFriendv5.Entitiy.User;
import com.GMorgan.RateMyFriendv5.Repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserService {
    private UserRepository repository;

    public boolean login(String username, String password) {
        List<User> userList = repository.findByUsername(username);
        boolean isSuccessful = userList.get(0).isPassword(password);
        log.info("Username: {} isSucessful: {}", username, isSuccessful);
        return isSuccessful;
    }

     public boolean signUp(String email, String username, String password) {
        if (userEmailExists(email) || userUsernameExists(username)) return false;
        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(Role.USER);
        repository.save(user);
        log.info("User email: {} username: {}", email, username);
        return true;
     }

    public boolean userEmailExists(String email) {
         return !repository.findByEmail(email).isEmpty();
    }

    public boolean userUsernameExists(String username) {
        return !repository.findByUsername(username).isEmpty();
    }
}

ConstantsController.java

package com.GMorgan.RateMyFriendv5.Controller;

import com.GMorgan.RateMyFriendv5.Utils.Mappings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConstantsController {

    @Value("${controller.constant.ping.message}")
    public String pingMessage;

    @RequestMapping(Mappings.PING)
    public String ping() {
        return pingMessage;
    } 
}

ConstantsControllerTest

@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class ConstantsControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Value("${controller.constant.ping.message}")
    public String pingMessage;

    @Test
    public void pingTest() throws Exception {
this.mockMvc.perform(get(Mappings.PING)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString(pingMessage)));
    }
}

我希望测试通过。在运行时,当我转到链接时,会看到ping消息。我也希望测试也这样做。

1 个答案:

答案 0 :(得分:1)

您需要指定要测试的控制器:

在您的注释中添加@WebMvcTest(ConstantsController.class)