Search code examples
javajunitmockitojmock

Mock a static method


I want to write a test case that will verify a method in my class. I have a local ApplicationLauncher object in my method that has to be mocked because it calls a method, launch(), which should not be called in a unit test.

public class RunApp
{
   public void check(String name)
   {
     if(name !=null)
     {
       ApplicationLauncher launcher = Application.getLauncher("launch");
       String appName = name+".bat";
       launcher.launch(appName);
     }
   }
 }

My JUnit test code is below:

RunApp runapp = new RunApp();

@Mock
ApplicationLauncher launcher;

@Test
public void test()
{
  runapp.check("test");
  verify(launcher,atLeastOnce).launch(anyString());
}

I am not able to return a mock object like

when(Application.getLauncher(anyString())).thenReturn(launcher);

since getLauncher is a static method in Application class. How can I solve this?


Solution

  • A better application design might be to have ApplicationLauncher as an interface and create production and test implementations (or just mock the test implementation). You would need to pass an instance of ApplicationLauncher into your RunApp class, perhaps in the constructor.