Anarkie
Anarkie

Reputation: 695

Junit how to mock method return in test method?

I was getting a NullPointerException with following method's test but after comments I edited my code and now getting following error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ...

My source code is at src/main/java and test is at src/test/java but this doesnt play much of a big role, I moved the test class in main/java and didnt help.

@Component
public class MyClass {

@Autowired
MyService myService;

public void myMethod(Dog dog, Animal animal) { 
    if (myService.isAnimal(dog.getStatus()) {//NPE was on this line
      dog.setName("mike");
    } else {
      dog.setName(null);
    }
}
}

Below is test code:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyClass.class)
public class MyClassTest {

@Autowired
MyClass testObjMyClass;

@Test
public void testMyMethod() {

MyService myService = mock(MyService.class);

Dog dog = new Dog();
dog.setStatus("Y"); // this should give true for isAnimal()
when(myService.isAnimal(dog.getStatus())).thenReturn(true); // I tried with ("Y") as well

testObjMyClass.myMethod(dog, animal);// I defined animal in test Class variables before.
assertEquals("mike", dog.getName());
}

}

My project is springboot application, myService is autowired in myMethod(). I would appreciuate your tips!

Upvotes: 0

Views: 3101

Answers (2)

Mansoor Ali
Mansoor Ali

Reputation: 153

You are mocking the class MyService but you are not injecting that mock into MyClass. Try this if you are using mockito

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

            @Mock
            MyService myService;

            @InjectMocks
            MyClass testObjMyClass;

            @Before
            public void setup() {
                MockitoAnnotations.initMocks(this);
                when(myService.isAnimal(dog.getStatus())).thenReturn(true);
            }

            @Test
            public void testMyMethod() {

                Dog dog = new Dog();
                dog.setStatus("Y"); // this should give true for isAnimal()

                testObjMyClass.myMethod(dog, animal);// I defined animal in test Class variables before.
                assertEquals("mike", dog.getName());
            }

        }

Upvotes: 1

miljon
miljon

Reputation: 2781

If you have spring boot 1.4 or above try to replace annotation in test with these:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)

It's simplification created by Spring team

If you have Spring boot lower than 1.4 (i.e. 1.3) the you have to add loader to your ContextConfiguration:

@ContextConfiguration(classes=MyClass.class, loader=SpringApplicationContextLoader.class)

Upvotes: 1

Related Questions