使用MongoRepository测试查询

时间:2018-02-10 22:16:41

标签: java spring mongodb spring-boot junit

我正在尝试在控制器上运行测试,该控制器调用服务' findByEmailAddress'。从存储库&CustomerConpository'中调用此方法。它使用' @ Query'用于获取所需内容的注释。当我运行测试时,它在服务调用时返回一个空指针异常。

这是我的控制人员:

MOV[B]

存储库:

CMP[B]

服务:

@Controller
public class CustomerLoginController {

@Autowired
private CustomerService customerService;


@RequestMapping(value = "/customer/registration", method = RequestMethod.POST)
public ModelAndView createCustomer(@Valid Customer customer, BindingResult bindingResult) {
    ModelAndView modelAndView = new ModelAndView();
    Customer customerExists = customerService.findByEmailAddress(customer.getEmail());

    if (customerExists != null) {
        //do some stuff
    }

    if (bindingResult.hasErrors()) {
        modelAndView.setViewName("view1");
    } else {
        customerService.save(customer);
        modelAndView.addObject("message", "Created!");
        modelAndView.setViewName("view2");
    }

    return modelAndView;

}

}

JUnitTest:

public interface CustomerRepository extends MongoRepository<Customer, String> {

    @Query(value = "{ 'email' : ?0}")
    Customer findByEmail(String email);

}

打破这一行:

@Service
public class CustomerServiceImpl implements CustomerService {

    @Override
    public Customer findByEmailAddress(String email) {
        return customerRepository.findByEmail(email);
   }

}

例外:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerControllerTests {

    @InjectMocks
    private CustomerLoginController customerLoginController;

    @Mock
    private CustomerService customerService;

    @Mock
    private BindingResult bindingResult;

    @Before
    public void setup() {
        customer = mockCustomer();
        customerLoginController = new CustomerLoginController();
    }

    @Test
    public void shouldReturnUserToLoginPage_WhenBindingResultHasErrors() throws Exception {
        when(customerService.findByEmailAddress(Constants.CUSTOMER_EMAIL)).thenReturn(customer);
        when(bindingResult.hasErrors()).thenReturn(true);
        ModelAndView modelAndView = customerLoginController.createCustomer(customer, bindingResult);
        assertThat(modelAndView.getViewName(), equalTo("view1"));
    }
}

0 个答案:

没有答案