Pregunta

I have a service class MyService which is defined and being used in controller like so:

public interface MyService {
  public String someMethod() 
}

@Service("myService")
public class MyServiceImpl implements MyService {
  public String someMethod() {
    return "something";
  }
}

@Controller 
public class MyController {
  @Autowired
  public MyService myService;

  @RequestMapping(value="/someurl", method=RequestMethod.GET)
  public String blah () {
    return myService.getsomeMethod();
  }
}

I'd like to write a test case for the someMethod method, however, the following doesn't work. How can I wire in the implementation class?

public class MyServiceImplTest {
 @Autowired
 private MyService myService;

 @Test
 public void testSomeMethod() {
   assertEquals("something", myService.someMethod());
 }

}

¿Fue útil?

Solución

public class MyServiceImplTest {
    private MyService myService = new MyServiceImpl();

    @Test
    public void testSomeMethod() {
        assertEquals("something", myService.someMethod());
    }
}

Why inject the bean in your test rather than creating an instance by yourself?

Otros consejos

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
 // specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")

Also see the Spring.IO docs for more detail.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top