Search code examples
javaspringunit-testingjunitjmockit

Injecting only some properties, mocking others


I am writing a unit test for a Bean that has some properties autowired in using spring.

Here is the bean:

public class Goober {

     @Autowired
     private ObjectX prop1;

     @Autowired
     private ObjectY prop2;


     //... rest of object
}

In my unit test, I'd like to Mock prop1 using jmockit, but have prop2 injected by spring. Here is what my test looks like:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext-test.xml" })
public class GooberUT extends TestCase{

    @Tested @Autowired
    Goober goober;

    @Test
    public void gooberTest (@Injectable prop1) {


        // .. test and whatnot here
    }


    // .. setup/teardown etc
}

The problem here is that prop1 will be autowired by spring. If I remove the @Autowired annotation from the test, then prop1 will be mocked, but prop2 will be null.

How do I inject one property in Goober with jMockit, and Autowire the other?


Solution

  • You can let Spring inject prop1 and then override the prop1 value with ReflectionTestUtils' setProperty method and inject whatever you like programmatically.