The method that i need to unit test logs the output in the following way and doesnt return anything. How do i write a unit test method for the following case? Please help i'm new to this concept and havent written any test methods before
private void revoke (params) {
if (userexist (revokedb, userid))``
{
deleteusers (revokedb, userid);
if (userexist (revokedb, userid))
{
logger.info ("Not able to delete user");
}
else
{
logger.info ("User was succesfully deleted");
}
else
{
logger.info ("unable of find the user");
}
}
Check out moq
https://github.com/Moq/moq4
your logger needs to implement an interface that you can then mock.
Eg
MyLogger:ILogger
ILogger
would define the method info(string)
in your test, you'd set up your mock first
var mock = new Mock<ILoveThisLibrary>();
and then you can inject this mock into your class (where logger
) is used. Either through the constructir or any other method that replaces the actual logger with this mock object. This is called dependency injection.
Now all calls to logger
will get directed to your mock object and you can do all sorts of mocking. Eg expectations, ie checking that info
was called with the string that you expect.
I think you can inject the logger in the class constructor like below.
public class BusService : IBusService
{
private readonly ILogger _logger;
public BusService(ILogger<BusService> logger)
{
_logger = logger;
}
private void revoke (params) {
if (userexist (revokedb, userid))``
{
deleteusers (revokedb, userid);
if (userexist (revokedb, userid))
{
_logger.info ("Not able to delete user");
}
else
{
_logger.info ("User was successfully deleted");
}
else
{
_logger.info ("unable of find the user");
}
}
}
Once it is injected in class constructor like above, you can use Moq class to mock your logger like below test method.
[Fact]
public void BusService_revoke_deleteUser()
{
// Arrange
var logger = Mock.Of<ILogger<BusService>>();
var busService = new BusService(logger);
// Act
var result = busService.revoke(params);
// Assert
// Assert statement will go here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.