I need test my database that, when I insert duplicate value in specific column where I have constraint, it fire exception. Can you show me how can I simulate second same call and fire exception?
here is my code, but doesn't work:
@RunWith(MockitoJUnitRunner.class)
public class SomeTestClass {
@InjectMocks
private FooService service = new FooServiceImpl();
@Test(expected = DataIntegrityViolationException.class)
public void myTest() {
// init Foo object here
service.createFoo(myFoo); // here should pass
service.createFoo(myFoo); // here shouldn't
}
}
I can't show original FooServiceImpl but the basic concept is here:
@Transactional
public void createFoo(Foo foo) {
MainFoo mainFoo = new MainFoo();
SomeObj obj1 = objService.findOne(foo.getId());
mainFoo.setObj(obj1);
fooRepository.save(mainFoo);
}
What I do wrong? Thanks.
I am not really sure if you want to test your actual database or you just need to mock the DB call.In case you just want to test your service class better mock the second statement using.
Also, If you are using spring, All you need to do is use
@InjectMocks
and mock the dependencies of the respected class using@Mock
.For consecutive calls you can use: