Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EntityManager.detach method is not working when testing using JUnit #6

Closed
eronekogin opened this issue Jul 15, 2020 · 1 comment
Closed

Comments

@eronekogin
Copy link

Hello Ranga,

I am learning the course associated with this repo and I am at the Step#12 of Chapter#5, which is to play with the entitymanager.

This is the target method in my CourseRepository class:

public Long checkDetach() {
        Course course = new Course("HAPPY PYTHON");
        em.persist(course);
        em.flush();
        em.detach(course);
        course.setName("HAPPY MORE PYTHON");
        return course.getId();
    }

And this is the test method I wrote for the above method:

    @Test
    @DirtiesContext
    public void testCheckDetach() {
        // Case will fail in unit testing.
        Long newId = courseRepository.checkPersistence();
        Course course = courseRepository.findById(newId);
        assertEquals("HAPPY PYTHON", course.getName());
    }

The above test case will not pass as the target course entity is still updated even after it was detached.

However, if running the application directly with the below method defined in the run method as follows:

	@Override
	public void run(String... args) throws Exception {
		courseRepository.checkDetach();
	}

This will correctly reflect what the checkDetach() specifies, which will successfully detach the target course entity and will not update the associated entry in the h2 database.

So I am quite confused and wondering what I missed to create a correct unit test case for the checkDetach method and I would really appreciate if you could provide some suggestions on that.

@eronekogin
Copy link
Author

It turns out that I was using an incorrect method when writing my test method, which should use checkDetach instead of checkPersistence. I guess that was simply caused by a copypaste and really sorry for open it as an issue here. Now everything is working for me, so I will close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant