filemonczyk filemonczyk - 3 months ago 9
Java Question

Running tests with spring boot

So I'm trying to test Spring boot MVC app that I wrote:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PetClinicApplication.class)
@WebAppConfiguration
public class OwnerControllerTests {
@Mock
private OwnerService ownerService;

@InjectMocks
private OwnerController ownerController;

private MockMvc mockMvc;

public void setup(){
MockitoAnnotations.initMocks(this);

mockMvc = MockMvcBuilders.standaloneSetup(ownerController).build();
}

@Test
public void testOwnerList() throws Exception{
List<Owner> owners = new ArrayList<>();
owners.add(new Owner());
owners.add(new Owner());

when(ownerService.getAll()).thenReturn((List<Owner>) owners);

mockMvc.perform(get("/ownerList"))
.andExpect(status().isOk())
.andExpect(view().name("ownerList"))
.andExpect(model().attribute("ownerList", List.class));

}

}


And im gettin in line

when(ownerService.getAll()).thenReturn((List<Owner>) owners);


in debugger mode ownerService=null
this is OwnerService.class

@Transactional
public Collection<Owner> getAll() {
return ownerDao.getAll();
}


this method should retrun list of Owner.class objects

owner controller snippet

@Controller
public class OwnerController {

@Autowired
private OwnerService ownerService;

@RequestMapping("/addOwner")
public String addOwner(Model model) {
model.addAttribute("Owner", new Owner());
return "addOwner";
}

@RequestMapping(value = "addOwner.do", method = RequestMethod.POST)
public String addOwnerDo(@Valid @ModelAttribute(value = "Owner") Owner owner, BindingResult result) {

if (result.hasErrors())
return "addOwner";
ObjectBinder.bind(owner);
ownerService.add(owner);
return "redirect:addOwner";
}

@RequestMapping("/ownerList")
public String ownerList(Model model) {
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}

@RequestMapping("/ownerList/{id}")
public String ownerDetails(@PathVariable(value = "id") int id, Model model) {
Owner owner = ownerService.get(id);
model.addAttribute("owner", owner);
return "ownerDetail";
}

// to refactor
@RequestMapping(value = "/ownerList/{id}.do")
public String ownerDetailsDo(@ModelAttribute(value = "owner") Owner owner, BindingResult result,
@RequestParam(value = "action") String action, Model model) {


switch (action) {
case "update":
ObjectBinder.bind(owner);
ownerService.update(owner);
return "ownerDetail";
case "delete":
ownerService.remove(owner.getId());
model.addAttribute("ownerList", ownerService.getAll());
return "ownerList";
}
model.addAttribute("owner", owner);
return "ownerDetail";
}



}

Answer

You forgot to annotate your setup method with @Before such that mockito do not create and inject the mocks, try this:

@Before
public void setup(){
   ...
}