3

Im trying to write a JUnit test for a method in my spring controller, but I cant seem to get the test right. It doesn't seem to autowire the db connection in the controller when i'm testing.

The controller

@Controller
public class PollController {

    @Autowired
    private PollRepository pollrepo;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getPoll(@PathVariable String id, Model model) {
        try {
            Poll poll = pollrepo.findById(id);
            if(poll == null) throw new Exception("Poll not found");
            model.addAttribute("poll", poll);
            return "vote";
        } catch (Exception e) {
            return "redirect:/errorpage";
        }
    }
}

and the JUnit test class

public class PollControllerTest {

    public PollControllerTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }


    @Test
    public void testGetPoll() {
        System.out.println("getPoll");
        String id = "5856ca5f4d0e2e1d10ba52c6";
        Model model = new BindingAwareModelMap();
        PollController instance = new PollController();
        String expResult = "vote";
        String result = instance.getPoll(id, model);
        assertEquals(expResult, result);
    }
}

Am I missing something here?

2 Answers 2

1

It will not autowire database connection because the controller instance in your junit is not managed by spring container.

You have created instance of PollController using keyword new and hence it is not a spring managed bean.

PollController instance = new PollController();

I would recommend to annotate your test class with @RunWith(SpringJUnit4ClassRunner.class) and inject controllers for tests,

@RunWith(SpringJUnit4ClassRunner.class)
class PollControllerTest {

    //Object under test
    @Autowired
    PollController instance;
Sign up to request clarification or add additional context in comments.

5 Comments

When I try doing this it gives me the following error: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'poll.PollControllerTest': Unsatisfied dependency expressed through field 'instance'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'poll.PollController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
add your configuration xml file. I suspect you have not used the annotation config and component scan configuration.
I have none it seems, so that might be the problem?
@Pegaseus you need to configure your controller and other components to be available in the spring application context using configuration. You need to work on those things. However if you find junit related answer helpful please accept so that it can be useful for others as well.
How would I do this, because I'm kinda getting lost in Spring, just started using it and it confuses me.
0

Yes. pollrepo is an external dependency so you need to mock it in your test class. refer the below code.

class PollControllerTest {

    //Object under test
    PollController instance;

    @Mock
    private PollRepository pollrepo;

    @Before
    public void setUp() {

        instance = new PollController();

        ReflectionTestUtils.setField(instance, "pollrepo", pollrepo);
    }

    //Tests goes here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.