Spring - 在另一个类中设置autowired对象以进行junit测试

时间:2016-04-20 20:00:07

标签: spring spring-mvc junit factory

我有一个类控制器: 问题在Test类的注释中 - 我应该如何模拟myFactory对象并将此对象设置为控制器的属性?即使我使用@Mock / EasyMock模拟工厂对象,我应该如何在自动装配中将其设置在控制器中,它没有工厂的设置器             所以,我不能使用controller.setFactory()             另外,我如何模拟工厂对象中的方法,我使用@Mock对象的方式:Mockito.when(factory.someFactoryMethod).andReturn(" abc")

public class Controller{
    @Autowired
    MyFactory factory;

    someMethod(){
        String abh = factory.someFactoryMethod("defaultObject");
    }
}

public class MyFactory{
    public String someFactoryMethod(String argument){
        //some code
    }
}


public class ControllerTest{
    @Before
    public void initialize() {
       Controller testController = spy(new Controller());
           /*
        how should I mock myFactory object and set this object as a property of controller? Even if I mock the factory object using @Mock/ EasyMock, how should I set this in controller as with Autowiring, it does not have the setter for factory
        So, I cant use controller.setFactory(<mocked object>)
        Also, How do I mock the methods in factory object , the way I do it for objects with @Mock : Mockito.when(factory.someFactoryMethod).andReturn("abc") 
        */
    }
}

2 个答案:

答案 0 :(得分:2)

我建议至少在构造函数lvl上自动装配:

private final MyFactory factory;

@Autowired
public Controller(MyFactory factory) {
  this.factory = factory;
}

在测试中,您可以模拟(通过Mockito或创建自己的模型)或将具体实例传递给Controller:

@Before
public void initialize() {
  private Controller testController = new Controller(factory);
}

要模拟工厂并使用您指定的given,您可以像这样嘲笑它:

MyFactory factory = Mockito.mock(MyFactory.class);

编辑(使用注释) 此测试类也可以作为您使用Mockito基于注释的模拟的示例:https://github.com/gmaslowski/spock-groovy-sample/blob/master/src/test/java/com/gmaslowski/spock/sample/DummyServiceTest.java

答案 1 :(得分:0)

您可以将@InjectMocks@Spy

结合使用
public class ControllerTest{
    @Mock
    MyFactory factory;

    @Spy
    @InjectMocks
    Controller testController;

    @Before
    public void initialize() {
        //expectations
    }
}